|
|
|
|
|
by vanderZwan
1630 days ago
|
|
/** Return this symbol to skip the current value. */
const SKIP = Symbol("mapFilter.SKIP");
/**
* @template T, R
* @param {T[]} array
* @param {(SKIP: Symbol, currentValue: T, index: number, array: T[]) => R|SKIP} callback return `SKIP` to filter out an element
* @param {number} [begin] defaults to 0
* @param {number} [end] defaults to `array.length`
* @returns {R[]}
*/
function mapFilter(array, callback, begin = 0, end = array.length) {
const ret = [];
for (let i = begin; i < end; i++) {
const v = callback(SKIP, array[i], i, array);
if (v !== SKIP) ret.push( /** @type {R} */ (v));
}
return ret;
};
Here. Less than ten lines without JSDoc type annotations, twenty with them. It lets you slice, map and filter all in one call without allocating intermediate arrays like you would when chaining them, making it almost as fast as a plain for-loop. It's also easy to turn it into an in-place version, removing even the array allocation overhead. |
|