Skip to content

Commit

Permalink
feat: Update "map" to allow curried and un-curried calling.
Browse files Browse the repository at this point in the history
BREAKING CHANGE:
Multiple functions can be passed if wrapped in array.

```js
// old
map(inc, inc)([1, 2])

// new
map([inc, inc], [1, 2])
```
  • Loading branch information
andreidmt committed Aug 26, 2020
1 parent fde6d39 commit eea3954
Show file tree
Hide file tree
Showing 2 changed files with 56 additions and 22 deletions.
70 changes: 49 additions & 21 deletions src/map/map.js
Original file line number Diff line number Diff line change
@@ -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)
}
8 changes: 7 additions & 1 deletion src/map/map.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -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],
Expand All @@ -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]"
)
Expand Down

0 comments on commit eea3954

Please sign in to comment.