Skip to content

Instantly share code, notes, and snippets.

@tunnckoCore
Created October 2, 2017 15:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tunnckoCore/f9941b4d102a906e40e297083e73bd10 to your computer and use it in GitHub Desktop.
Save tunnckoCore/f9941b4d102a906e40e297083e73bd10 to your computer and use it in GitHub Desktop.
basic arithmetic memoization - failed try
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