Skip to content

Instantly share code, notes, and snippets.

@tunnckoCore
Created Oct 2, 2017
Embed
What would you like to do?
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