Skip to content

Instantly share code, notes, and snippets.

@aquaductape
Last active June 19, 2019 20:54
Show Gist options
  • Save aquaductape/b59762be38cb8e68137c240aa53ba1e7 to your computer and use it in GitHub Desktop.
Save aquaductape/b59762be38cb8e68137c240aa53ba1e7 to your computer and use it in GitHub Desktop.
emulating find 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, 'myFind', {
// 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++) {
// most methods ignore empty slots but this one doesn't
// if (i in this) {
if (callback.apply(context, [this[i], i, this])) {
return this[i];
}
// }
}
},
});
// class alternative, safe since methods are locally scoped
class MyMethods {
constructor() {}
find(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 (callback.apply(context, [arr[i], i, arr])) {
return arr[i];
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment