Created
October 2, 2017 15:29
-
-
Save tunnckoCore/f9941b4d102a906e40e297083e73bd10 to your computer and use it in GitHub Desktop.
basic arithmetic memoization - failed try
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 app = require('parse-function')() | |
let cacheHits = 0 | |
const cache = {} | |
function memoizeArithmetic(arithmeticExpr) { | |
function __memoizedArithmeticFn__() { | |
// not too efficient! probably `split` could be used.. | |
const key = app | |
.parse(arithmeticExpr) | |
.body.trim() | |
.replace(/\s/, '') | |
if (cache.hasOwnProperty(key)) { | |
console.log('hits', (cacheHits = cacheHits + 1)) | |
return cache[key] | |
} | |
console.log('cached!') | |
return (cache[key] = arithmeticExpr()) | |
} | |
__memoizedArithmeticFn__.__proto__.__isArithmeticExpression = true | |
return __memoizedArithmeticFn__ | |
} | |
// const basic = memoizeArithmetic(() => (1 + 2) / 6) | |
// const basic2 = () => (1 + 2) / 6 | |
// console.log(basic.__isArithmeticExpression) | |
// console.log(basic2.__isArithmeticExpression) | |
let i = 0 | |
Function.prototype.call = new Proxy(Function.prototype.call, { | |
apply: (targetFn, ctx, args) => { | |
if (targetFn.__isArithmeticExpression) { | |
return targetFn | |
} | |
return Reflect.apply(targetFn, ctx, args) | |
}, | |
}) | |
const foo = memoizeArithmetic((a, b) => `${a} hi ${b}`) | |
// console.log(i) | |
console.log(foo.call()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment