Created
November 3, 2017 11:58
-
-
Save unlabeled/318f192362b4529bf268f3c54f14277c 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 cached = new WeakMap() | |
/** | |
* Check two arrays to equal | |
* | |
* @param {Array} firstParams | |
* @param {Array} secondParams | |
* @returns {boolean} | |
*/ | |
function isEqual(firstParams, secondParams) { | |
const lengthFirstParams = firstParams.length | |
const lengthSecondParams = secondParams.length | |
if (lengthFirstParams !== lengthSecondParams) { | |
return false | |
} | |
let condition = true | |
for (let i = 0; i < lengthFirstParams; i++) { | |
if (firstParams[i] !== secondParams[i]) { | |
condition = false | |
break | |
} | |
} | |
return condition | |
} | |
/** | |
* Cache binded function result with its params | |
* | |
* @param {Function} fn | |
* @param {Array} args | |
* @returns {Function} | |
*/ | |
export function bindArg(fn, ...args) { | |
if (!cached.has(fn)) { | |
const bindedFunction = fn.bind(undefined, ...args) | |
const argsFunction = new Map() | |
argsFunction.set(bindedFunction, args) | |
cached.set(fn, argsFunction) | |
return bindedFunction | |
} | |
const found = cached.get(fn) | |
for (const [bindedFunction, storedArgs] of found) { | |
if (isEqual(storedArgs, args)) { | |
return bindedFunction | |
} | |
} | |
const bindedFunction = fn.bind(undefined, ...args) | |
found.set(bindedFunction, args) | |
return bindedFunction | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment