Skip to content

Instantly share code, notes, and snippets.

@petsel
Last active July 27, 2021 17:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save petsel/32c1a499c9a6fbb05edc3f29dec1c542 to your computer and use it in GitHub Desktop.
Save petsel/32c1a499c9a6fbb05edc3f29dec1c542 to your computer and use it in GitHub Desktop.
const
arrPrototype = Object.getPrototypeOf([]);
const {
from: arrayFrom,
isArray,
} = Array;
function isFunction(type) {
return (
(typeof type === 'function')
&& (typeof type.call === 'function')
&& (typeof type.apply === 'function')
);
}
function getSanitizedTarget(type) {
return (type ?? null);
}
function forEachWithStopIteration(callback, target) {
const arr = ((isArray(this) && this) || arrayFrom(this ?? []));
// fail silently.
if (arr && isFunction(callback)) {
let proceed = true;
const stopIteration = () => proceed = false;
target = getSanitizedTarget(target);
let idx = -1;
const len = arr.length;
while (proceed && (++idx < len)) {
// acknowledge sparse array slots.
if (idx in arr) {
callback.call(target, arr[idx], idx, arr, stopIteration);
}
}
}
}
Object.defineProperty(arrPrototype, 'forEachSI', {
configurable: true,
writable: true,
value: forEachWithStopIteration
});
Object.defineProperty(arrPrototype.forEachSI, 'toString', {
value: () => 'function forEachSI() { [custom code] }'
});
// export default Array;
/*
(new Array(100))
.fill(null)
.forEachSI(function (elm, idx, arr, stopIteration) {
console.log([this, idx]);
if (idx > 4) {
stopIteration();
}
}, "foo");
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment