From fe6bb4665d8e105c0056227bf8393748f4cc01ed Mon Sep 17 00:00:00 2001 From: Andrei Dumitrescu <5057797+andreidcm@users.noreply.github.com> Date: Sun, 30 Aug 2020 13:07:07 +0200 Subject: [PATCH] feat(repeat): Update to allow uncurried call --- src/repeat/repeat.js | 41 ++++++++++++++++++++++++++------------- src/repeat/repeat.test.js | 15 +++++++------- 2 files changed, 35 insertions(+), 21 deletions(-) diff --git a/src/repeat/repeat.js b/src/repeat/repeat.js index e241e4a..1874992 100644 --- a/src/repeat/repeat.js +++ b/src/repeat/repeat.js @@ -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 } diff --git a/src/repeat/repeat.test.js b/src/repeat/repeat.test.js index b60558c..8263f8d 100644 --- a/src/repeat/repeat.test.js +++ b/src/repeat/repeat.test.js @@ -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() })