Last active
June 27, 2019 16:31
-
-
Save aquaductape/0498570ce0d1eeae0e52a4bc5a1e3a27 to your computer and use it in GitHub Desktop.
emulating filter 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, 'myFilter', { | |
// if callback is arrow function then context will be set to outer scope regardless of providing context argument | |
value: function(callback, context) { | |
// Good example for using the context with regular function expression | |
// const as = new Set([1, 2, 3]); | |
// const bs = new Set([3, 2, 4]); | |
// const intersection = [...as].filter(bs.has, bs); // [2, 3] | |
if (typeof callback !== 'function') { | |
throw new Error(`${callback} is not a function`); | |
} | |
const length = this.length; | |
const newArr = []; | |
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])) { | |
newArr.push(this[i]); | |
} | |
} | |
} | |
return newArr; | |
}, | |
}); | |
// class alternative, safe since methods are locally scoped | |
class MyMethods { | |
constructor() {} | |
filter(arr, callback, context) { | |
if (typeof callback !== 'function') { | |
throw new TypeError(`${callback} is not a function`); | |
} | |
const length = arr.length; | |
const newArr = []; | |
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])) { | |
newArr.push(arr[i]); | |
} | |
} | |
} | |
return newArr; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment