Skip to content

Commit 81de232

Browse files
committed
feat: Add function repeatFn()
1 parent 67e8182 commit 81de232

File tree

2 files changed

+29
-4
lines changed

2 files changed

+29
-4
lines changed

src/sequence.js

Lines changed: 21 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -215,13 +215,30 @@ function* range(start, end) {
215215
*/
216216
const range0 = b => range(0, b);
217217

218-
/** Generates an infinite iterator of the given value. */
219-
function* repeat(val) {
218+
/**
219+
* Generates an infinite iterator by invoking the
220+
* given function repeatedly.
221+
*
222+
* @function
223+
* @param {Function} fn
224+
* @returns {Sequence}
225+
*/
226+
function* repeatFn(fn) {
220227
while (true) {
221-
yield val;
228+
yield fn();
222229
}
223230
}
224231

232+
/**
233+
* Generates an infinite iterator of the given value.
234+
*
235+
* @function
236+
* @template T
237+
* @param {T} val
238+
* @returns {Sequence<T>}
239+
*/
240+
const repeat = val => repeatFn(() => val);
241+
225242
/**
226243
* Generate a sequence by repeatedly calling the same function on the
227244
* previous value.
@@ -1616,6 +1633,7 @@ module.exports = {
16161633
iter,
16171634
range,
16181635
range0,
1636+
repeatFn,
16191637
repeat,
16201638
extend,
16211639
extend1,

test/sequence.test.js

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ const assert = require('assert');
1717
const {
1818
and, plus, or, mul, not,
1919
size, TraitNotImplemented, _typedArrays,
20-
iter, range, range0, repeat, extend, extend1, flattenTree,
20+
iter, range, range0, repeat, repeatFn, extend, extend1, flattenTree,
2121
IteratorEnded, next, tryNext, nth, first, second, last, tryNth, tryFirst,
2222
trySecond, tryLast, seqEq, each, find, tryFind, contains, count, list,
2323
uniq, join, dict, obj, into, foldl, foldr, any, all, sum, product, map,
@@ -111,6 +111,13 @@ it('range(), range0()', () => {
111111

112112
it('repeat()', () => {
113113
ckEqSeq(tryTake(repeat(2), 4), [2, 2, 2, 2]);
114+
115+
let x = 0;
116+
const fn = () => {
117+
x += 1;
118+
return x;
119+
};
120+
ckEqSeq(tryTake(repeatFn(fn), 4), [1, 2, 3, 4]);
114121
});
115122

116123
it('extend(), extend1()', () => {

0 commit comments

Comments
 (0)