Skip to content

Instantly share code, notes, and snippets.

@aquaductape
Last active June 19, 2019 20:58
Show Gist options
  • Save aquaductape/bad001e05ff454cdb850763e27bdfc2d to your computer and use it in GitHub Desktop.
Save aquaductape/bad001e05ff454cdb850763e27bdfc2d to your computer and use it in GitHub Desktop.
emulation of every method
// Array prototype method, however this is not safe, since it is added to the global scope
// definedProperty makes method non-enumerable as well as adding new property to in this case, to Array prototype
Object.defineProperty(Array.prototype, 'myEvery', {
// if callback is arrow function then context will be set to outer scope regardless of providing context argument
value: function(callback, context) {
if (typeof callback !== 'function') {
throw new TypeError(`${callback} is not a function`);
}
const length = this.length;
for (let i = 0; i < length; i++) {
// check sparse array ex. [1, , ,2]
if (i in this) {
if (!callback.apply(context, [this[i], i, this])) {
return false;
}
}
}
return true;
},
});
// class alternative, safe since methods are locally scoped
class MyMethods {
constructor() {}
every(arr, callback, context) {
if (typeof callback !== 'function') {
throw new TypeError(`${callback} is not a function`);
}
const length = arr.length;
for (let i = 0; i < length; i++) {
if (i in arr) {
if (!callback.apply(context, [arr[i], i, arr])) {
return false;
}
}
}
return true;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment