Last active
June 19, 2019 21:00
-
-
Save aquaductape/2f9dda357429e8b87386c7ec53a1beb4 to your computer and use it in GitHub Desktop.
emulating some method
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
// 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, 'mySome', { | |
// 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 true; | |
} | |
} | |
} | |
return false; | |
}, | |
}); | |
// class alternative, safe since methods are locally scoped | |
class MyMethods { | |
constructor() {} | |
some(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++) { | |
// check sparse array ex. [1, , ,2] | |
if (i in arr) { | |
if (callback.apply(context, [arr[i], i, arr])) { | |
return true; | |
} | |
} | |
} | |
return false; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment