Convert the first element N in the fighter to an array

Something like the question Convert ES6 Iterable to Array . But I need only the first N elements. Are there any built-in features for me? Or how can I achieve this more elegantly?

let N = 100;
function *Z() { for (let i = 0; ; i++) yield i; }

// This wont work
// Array.from(Z()).slice(0, N);
// [...Z()].slice(0, N)

// This works, but a built-in may be preferred
let a = [], t = Z(); for (let i = 0; i < N; i++) a.push(t.next().value);
+4
source share
3 answers

To get the first nvalues iterator, you can use one of:

Array.from({length: n}, function(){ return this.next().value; }, iterator);
Array.from({length: n}, (i => () => i.next().value)(iterator));

To get iteratorarbitrary iterable, use:

const iterator = iterable[Symbol.iterator]();

In your case, given the function of the generator Z:

Array.from({length: 3}, function(){ return this.next().value; }, Z());

If you need this function more often, you can create a generator function:

function* take(iterable, length) {
  const iterator = iterable[Symbol.iterator]();
  while (length-- > 0) yield iterator.next().value;
}

// Example:
const set = new Set([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);
console.log(...take(set, 3));
Run code
 
+2
source

, (ala take()). for of, , :

let a = []; let i = 0; for (let x of Z()) { a.push(x); if (++i === N) break; }

, , iterable N .

+1

A little shorter and less efficient with .mapand a little safer with a custom function:

function *Z() { for (let i = 0; i < 5; ) yield i++; }

function buffer(t, n = -1, a = [], c) { 
    while (n-- && (c = t.next(), !c.done)) a.push(c.value); return a; }

const l = console.log, t = Z()

l( [...Array(3)].map(v => t.next().value) )

l( buffer(t) )
Run code
0
source

Source: https://habr.com/ru/post/1689992/


All Articles