Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- const factorial = () => {
- const cached = {}
- return function(num) {
- console.time('NOT')
- console.time('CHACHED')
- console.log(cached)
- if (cached[num]) {
- console.timeEnd('CHACHED')
- return cached[num]
- }
- let result = 1
- for (let i = 1; i <= num; i++) {
- result = result * i
- }
- console.timeEnd('NOT')
- cached[num] = result
- return result
- }
- }
- const memFact = factorial()
- console.log(memFact(50))
- console.log(memFact(50))
- const memoize = fn => {
- const cache = {}
- return (...args) => {
- let result
- console.time('NOT')
- console.time('CHACHED')
- if (cache[args[0]]) {
- console.timeEnd('CHACHED')
- return cache[args[0]]
- }
- result = fn(...args)
- console.timeEnd('NOT')
- cache[args[0]] = result
- return result
- }
- }
- const add = n => n + 10
- console.log('Simple call', add(3))
- const memoizedAdd = memoize(add)
- console.log(memoizedAdd(3))
- console.log(memoizedAdd(3))
- console.log(memoizedAdd(4))
- console.log(memoizedAdd(4))
Add Comment
Please, Sign In to add comment