diff --git a/src/map/map.js b/src/map/map.js index f5cc29e..8555e2a 100644 --- a/src/map/map.js +++ b/src/map/map.js @@ -1,28 +1,56 @@ -/** - * Iterate over an input list, calling `fn` for each element, return a new - * array - * - * @param {Function} fn The function - * @param {[]} list Array - * - * @return {Array} - */ -const map = (...fn) => source => { - const result = [] - const sourceArray = Array.isArray(source) ? source : [source] +import { pipe } from "../pipe/pipe" - for (let i = 0, valuesCount = sourceArray.length; i < valuesCount; i++) { - let value = sourceArray[i] - - // pipe functions through each value - for (let j = 0, fnCount = fn.length; j < fnCount; j++) { - value = fn[j].call(null, value, i, sourceArray) - } +const _map = (fn, _source) => { + const result = [] + const source = Array.isArray(_source) ? _source : [_source] - result.push(value) + for (let i = 0, valuesCount = source.length; i < valuesCount; ++i) { + result.push( + Array.isArray(fn) ? pipe(...fn)(source[i]) : fn(source[i], i, source) + ) } return result } -export { map } +/** + * Iterates over an array and applies a function on each element, returning a + * new array with the transformed elements. + * + * @param {Fn|Fn[]} fn Transform function called on all elements + * @param {[]} source Array to iterate over + * + * @return {Array} Returns new instance + * + * @tag Array + * @signature (fn: Fn|Fn[]) => (source: []) => [] + * @signature (fn: Fn|Fn[], source: []) => [] + * + * @example + * const inc = x => x + 1 + * + * map(inc, [1, 2]) + * // => [2, 3] + * + * map([inc, inc], [1, 2]) + * // => [3, 4] + */ +export const map = (...params) => { + /* + * @signature (fn: Fn|Fn[]) => (source: []): [] + * + * map(inc)([1, 2]) + * // => [2, 3] + */ + if (params.length === 1) { + return source => _map(params[0], source) + } + + /* + * @signature (fn: Fn|Fn[], source: []): [] + * + * map(inc, [1, 2]) + * // => [2, 3] + */ + return _map(...params) +} diff --git a/src/map/map.test.js b/src/map/map.test.js index 2a6f3d3..0a07d83 100644 --- a/src/map/map.test.js +++ b/src/map/map.test.js @@ -4,6 +4,12 @@ import { map } from ".." test("map", t => { const square = value => value * value + t.deepEqual( + map(square, [1, 2, 3]), + [1, 4, 9], + "(square, [1,2,3]) // => [1,4,9]" + ) + t.deepEqual( map(square)([1, 2, 3]), [1, 4, 9], @@ -17,7 +23,7 @@ test("map", t => { ) t.deepEqual( - map(square, square)([1, 2, 3]), + map([square, square], [1, 2, 3]), [1, 16, 81], "(square,square)([1,2,3]) // => [1,16,82]" )