Skip to content

Commit fbb3931

Browse files
author
Shil Sinha
committed
feat(iterate): add function to limit iteration
1 parent 36eb702 commit fbb3931

File tree

1 file changed

+22
-1
lines changed

1 file changed

+22
-1
lines changed

iterUtils.js

+22-1
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
const assert = require('assert');
12
const sift = require('sift').default;
23

34
/**
@@ -15,6 +16,17 @@ async function *filterIt(filter, iter) {
1516
}
1617
}
1718

19+
async function *limitIt(limit, iter) {
20+
let count = 0;
21+
for await (const item of iter) {
22+
yield item;
23+
24+
if (++count === limit) {
25+
break
26+
}
27+
}
28+
}
29+
1830
/**
1931
* @template T
2032
* @implements AsyncIterable<T>
@@ -61,6 +73,15 @@ class DecoratedIterable {
6173
}
6274
return result;
6375
}
76+
77+
/**
78+
* @param {number} limit
79+
* @return {DecoratedIterable<T>}
80+
*/
81+
limit(limit) {
82+
assert(limit && typeof limit === 'number', '"limit" must be a positive integer');
83+
return new DecoratedIterable(limitIt(limit, this));
84+
}
6485
}
6586

6687
module.exports = {
@@ -73,4 +94,4 @@ module.exports = {
7394
decorateIt(iter) {
7495
return new DecoratedIterable(iter);
7596
}
76-
};
97+
};

0 commit comments

Comments
 (0)