UNPKG

1.04 kBJavaScriptView Raw
1const objectHash = require('object-hash');
2const {memoizeNonPrimitives} = require('./memoize');
3const _ = require('lodash');
4
5let strHash = {};
6const hashString = str => {
7 if (!strHash[str]) {
8 strHash[str] = objectHash(str);
9 }
10 const res = strHash[str];
11 return res;
12};
13
14const clearHashStrings = () => {
15 strHash = {};
16}
17
18const exprHash = memoizeNonPrimitives(
19 obj => {
20 // console.log( Array.isArray(obj), _.isPlainObject(obj),JSON.stringify(obj, null,2))
21 if (Array.isArray(obj)) {
22 return objectHash(_.map(obj, val => exprHash(val)).join(','));
23 } else if (_.isPlainObject(obj)) {
24 const keys = Object.keys(obj).sort();
25 return objectHash(_.map(keys, key => `${key}:${exprHash(obj[key])}`).join(','));
26 } else if (_.isFunction(obj)) {
27 throw new TypeError(`Trying to chain a function in carmi code: ${obj}`)
28 } else {
29 return hashString(JSON.stringify(obj));
30 }
31 },
32 primitive => hashString(JSON.stringify(primitive))
33);
34
35module.exports = {exprHash, hashString, clearHashStrings};