Last active
March 24, 2019 04:46
-
-
Save sharmaabhinav/f20076543103d6776a4739b93131151f 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
var compare = function (obj1, obj2) { | |
if (obj1 === obj2) { | |
return true | |
} | |
var keyMap = {} | |
var obj1Keys = Object.keys(obj1) | |
var obj2Keys = Object.keys(obj2) | |
for(let key of obj1Keys) { | |
keyMap[key] = obj1[key] | |
} | |
for(let key of obj2Keys) { | |
if (keyMap[key] && keyMap[key] === obj2[key]) { | |
delete keyMap[key] | |
} else { | |
return false | |
} | |
} | |
return Object.keys(keyMap).length === 0 | |
} | |
function memo (fn) { | |
var map = new Map() | |
return function (arg) { | |
let returnVal = null | |
map.forEach((value, key) => { | |
if (compare(key, arg)) { | |
returnVal = value | |
} | |
}) | |
if (returnVal) { | |
return returnVal | |
} else { | |
map.set(arg, fn(arg)) | |
return map.get(arg) | |
} | |
} | |
} | |
const memoFunc = memo(person) | |
function person (obj) { | |
console.log('called') | |
return obj.firstName + ' ' + obj.lastName | |
} | |
console.log(memoFunc({firstName: 'abhinav', lastName: 'sharma'})) | |
console.log(memoFunc({firstName: 'abhinav', lastName: 'sharma'})) | |
console.log(memoFunc({firstName: 'kanika'})) | |
console.log(memoFunc({firstName: 'kanika'})) | |
console.log(memoFunc({firstName: 'kanika1'})) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment