Last active
July 27, 2021 17:38
-
-
Save petsel/32c1a499c9a6fbb05edc3f29dec1c542 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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