first version

This commit is contained in:
Conduitry 2018-03-17 16:23:31 -04:00
parent 7a0f611a1f
commit 588443ebe1
7 changed files with 90 additions and 0 deletions

7
.eslintrc.yaml Normal file
View File

@ -0,0 +1,7 @@
env:
es6: true
node: true
extends: 'eslint:recommended'
parserOptions:
ecmaVersion: 2017
sourceType: module

1
.gitignore vendored Normal file
View File

@ -0,0 +1 @@
/dist/

5
.prettierrc Normal file
View File

@ -0,0 +1,5 @@
printWidth: 100
useTabs: true
semi: false
singleQuote: true
trailingComma: all

21
package.json Normal file
View File

@ -0,0 +1,21 @@
{
"name": "memor",
"version": "0.1.0",
"description": "More memoization",
"main": "./dist/index.cjs.js",
"module": "./dist/index.es.js",
"files": ["dist"],
"engines": {
"node": ">=8"
},
"repository": {
"type": "git",
"url": "https://github.com/Conduitry/memor.git"
},
"author": "Conduitry",
"license": "MIT",
"bugs": {
"url": "https://github.com/Conduitry/memor/issues"
},
"homepage": "https://cndtr.io/memor/"
}

7
rollup.config.js Normal file
View File

@ -0,0 +1,7 @@
export default {
input: './src/index.js',
output: [
{ file: './dist/index.cjs.js', format: 'cjs', sourcemap: true },
{ file: './dist/index.es.js', format: 'es', sourcemap: true },
],
}

1
src/index.js Normal file
View File

@ -0,0 +1 @@
export { default as memoize } from './memoize.js'

48
src/memoize.js Normal file
View File

@ -0,0 +1,48 @@
let ARRAY = Symbol()
let POJO = Symbol()
let REGEXP = Symbol()
let DATE = Symbol()
let BUFFER = Symbol()
let array
let lookup
let recurse = obj => {
if (typeof obj === 'object' && obj !== null) {
let handler = lookup.get(Object.getPrototypeOf(obj))
if (handler) {
handler(obj)
return
}
}
array.push(obj)
}
lookup = new Map([
[Array.prototype, obj => (array.push(ARRAY, obj.length), obj.forEach(recurse))],
[
Object.prototype,
obj => (
array.push(POJO, Object.keys(obj).length, ...Object.keys(obj)),
Object.values(obj).forEach(recurse)
),
],
[RegExp.prototype, obj => array.push(REGEXP, obj.source, obj.flags)],
[Date.prototype, obj => array.push(DATE, obj.getTime())],
[Buffer.prototype, obj => array.push(BUFFER, obj.toString('base64'))],
])
let data = {}
export default func => (...args) => {
let here = data
array = []
recurse([func, ...args])
for (let key of array) {
let M = (typeof key === 'object' && key !== null) || typeof key === 'function' ? WeakMap : Map
if (!here[M.name]) here[M.name] = new M()
if (!here[M.name].has(key)) here[M.name].set(key, {})
here = here[M.name].get(key)
}
return 'value' in here ? here.value : (here.value = func(...args))
}