@naturalcycles/js-lib
Version:
Standard library for universal (browser + Node.js) javascript
51 lines (50 loc) • 1.46 kB
JavaScript
import { AsyncIterable2 } from '../iter/asyncIterable2.js';
import { Iterable2 } from '../iter/iterable2.js';
export function _range(fromIncl, toExcl, step = 1) {
if (toExcl === undefined) {
toExcl = fromIncl;
fromIncl = 0;
}
const a = [];
for (let i = fromIncl; i < toExcl; i += step) {
a.push(i);
}
return a;
}
/**
* Returns an array of `length` filled with `fill` primitive value.
* Performance-optimized implementation.
* `Array.from({ length }, () => fill)` shows ~25x perf regression in benchmarks
*
* Fill is Primitive, because it's safe to shallow-copy.
* If it was an object - it'll paste the same object reference, which can create bugs.
*/
export function _arrayFilled(length, fill) {
return Array(length).fill(fill);
}
export function _rangeIterable(fromIncl, toExcl, step = 1) {
if (toExcl === undefined) {
toExcl = fromIncl;
fromIncl = 0;
}
return Iterable2.of({
*[Symbol.iterator]() {
for (let i = fromIncl; i < toExcl; i += step) {
yield i;
}
},
});
}
export function _rangeAsyncIterable(fromIncl, toExcl, step = 1) {
if (toExcl === undefined) {
toExcl = fromIncl;
fromIncl = 0;
}
return AsyncIterable2.of({
async *[Symbol.asyncIterator]() {
for (let i = fromIncl; i < toExcl; i += step) {
yield i;
}
},
});
}