-
Notifications
You must be signed in to change notification settings - Fork 4
/
take.js
39 lines (32 loc) · 788 Bytes
/
take.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
/* eslint no-constant-condition: 0 */
/**
* Obliterator Take Function
* ==========================
*
* Function taking n or every value of the given iterator and returns them
* into an array.
*/
var iter = require('./iter.js');
/**
* Take.
*
* @param {Iterable} iterable - Target iterable.
* @param {number} [n] - Optional number of items to take.
* @return {array}
*/
module.exports = function take(iterable, n) {
var l = arguments.length > 1 ? n : Infinity,
array = l !== Infinity ? new Array(l) : [],
step,
i = 0;
var iterator = iter(iterable);
while (true) {
if (i === l) return array;
step = iterator.next();
if (step.done) {
if (i !== n) array.length = i;
return array;
}
array[i++] = step.value;
}
};