Browse Source

first version

master v0.1.0
Conduitry 2 years ago
parent
commit
588443ebe1
7 changed files with 90 additions and 0 deletions
  1. +7
    -0
      .eslintrc.yaml
  2. +1
    -0
      .gitignore
  3. +5
    -0
      .prettierrc
  4. +21
    -0
      package.json
  5. +7
    -0
      rollup.config.js
  6. +1
    -0
      src/index.js
  7. +48
    -0
      src/memoize.js

+ 7
- 0
.eslintrc.yaml View File

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

+ 1
- 0
.gitignore View File

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

+ 5
- 0
.prettierrc View File

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

+ 21
- 0
package.json 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
- 0
rollup.config.js 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
- 0
src/index.js View File

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

+ 48
- 0
src/memoize.js 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))
}

Loading…
Cancel
Save