Skip to content

Commit

Permalink
feat(repeat): Update to allow uncurried call
Browse files Browse the repository at this point in the history
  • Loading branch information
andreidmt committed Aug 30, 2020
1 parent 0912f27 commit fe6bb46
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 21 deletions.
41 changes: 27 additions & 14 deletions src/repeat/repeat.js
Original file line number Diff line number Diff line change
@@ -1,29 +1,42 @@
import { pipe } from "../pipe/pipe"

const _repeat = (_fn, count = 0) => {
const result = []
const fn = Array.isArray(_fn) ? pipe(..._fn) : _fn
const isFunction = typeof fn === "function"

for (let i = 0; i < count; i++) {
result.push(isFunction ? fn(i) : fn)
}

return result
}

/**
* Return an array of fixed size containing a specified value or function result
*
* @tag Array
* @signature (fn: Function|mixed) => (count:number): Array
*
* @param {Function|mixed} fn Function or value to repeat
* @param {number} count Number of times
* @param {Function|mixed} fn Function or value to repeat
* @param {Number} source Number of times
*
* @return {Array}
*
* @name repeat
* @tag Array
* @signature (fn: Function|mixed) => (count: Number): Array
*
* @example
* repeat(2)(3)
* // => [2, 2, 2]
*
* repeat(index=>index+1)(3)
* repeat(index => index + 1, 3)
* // => [1, 2, 3]
*/
const repeat = fn => (count = 0) => {
const result = []

for (let i = 0; i < count; i++) {
result.push(typeof fn === "function" ? fn.call(null, i) : fn)
export const repeat = (...params) => {
// @signature (fn) => (source)
if (params.length <= 1) {
return source => _repeat(params[0], source)
}

return result
// @signature (fn, source)
return _repeat(...params)
}

export { repeat }
15 changes: 8 additions & 7 deletions src/repeat/repeat.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,14 @@ import test from "tape"
import { repeat } from ".."

test("repeat", t => {
t.deepEqual(
repeat(index => index + 2)(5),
[2, 3, 4, 5, 6],
"Repeat function 5 times "
)
t.deepEqual(repeat(index => index + 2)(), [], "Repeat function 0 times")
t.deepEqual(repeat(3)(2), [3, 3], "Repeat value 2 times ")
const inc = x => x + 1

t.deepEqual(repeat(inc)(5), [1, 2, 3, 4, 5], "Repeat function curried")
t.deepEqual(repeat(inc, 2), [1, 2], "Repeat function uncurried ")
t.deepEqual(repeat([inc, inc], 2), [2, 3], "Repeat with function chain")

t.deepEqual(repeat(inc)(), [], "Repeat without count")
t.deepEqual(repeat(3, 2), [3, 3], "Repeat value curried ")

t.end()
})

0 comments on commit fe6bb46

Please sign in to comment.