IterArray
IterArray
is an iterable adapter that, given an iterable/generator or iterator, creates a new indexable lazy iterable that provides nth
and slice
methods.
Performance of IterArray instances are optimized for Array
and primitive string iterables.
Usage.
const iterable =iterable // 8const slicedIterable = iterable // IterArray([2, 8, 3])slicedIterable // 3;...slicedIterable // [2, 8, 3]for const x of iterableconsole // log 5 2 8 3 4 0 9for const x of slicedIterableconsole // log 2 8 3
API
constructor (iterable)
It creates a IterArray
instance that iterates over the same values as iterable
parameter or if iterable
is a function, then it iterates over the same values as iterable()
. It throws an exception if it is not passed an iterable, iterator or function that returns an iterable or an iterator.
Example:
const IterArray ={1248}const iterableByArray =;...iterableByArray // [1, 2, 3]const iterableBySet =;...iterableBySet // [4, 5, 6]const iterableByIterArray =;...iterableByIterArray // [1, 2, 3]const iterableByGenerator =;...iterableByGenerator // [1, 2, 4, 8]const iterableByIterator =;...iterableByIterator // [1, 2, 4, 8]const iterableByFunction =;...iterableByFunction // [4, 5, 6]
nth (index)
It returns the index
-th value that produces IterArray instance.
Internally, when .nth(index)
is called, the values between 0 and index are cached. Then, if it is called nth
with a lower index, no values are computed and if it is called with a greater index, only the values between index + 1
and the greater index are computed.
Example:
const IterArray =const iterable =iterable // 3iterable // 9iterable // 2iterable // undefinediterable // undefined
has (index)
It returns true if IterArray instance produces the index
-th value.
Example:
const IterArray =const iterable =iterable // trueiterable // trueiterable // trueiterable // falseiterable // false
slice (start, end)
It returns an IterArray instance that iterates over the same values as sliced iterable.
Internally, the slice
method does not slice the iterable, it just define a new iterable that iterates over sliced values (lazy evaluation). The sliced values of IterArray
instance are also cached to get better performance when it called more than once.
length
A property of IterArray instance that can be an integer positive number or Infinity
. The length
property can be determined with a finite number only if all of the values of IterArray instance are cached.
In general, while not all of the values of iterable are traversed, length
property is Infinity. However IterArray
makes optimizations for arrays and primitive strings caching the values when the IterArray instance is created. Then, length
is a finite number in a first instance.
Example:
const a =alength // Infinitya // 1alength // Infinitya // 2alength // Infinitya // undefinedalength // 2const b =blength // Infinity;...b // [1, 2]blength // 2const c =clength // 2const d =clength // 3
LICENSE
MIT