1 | const objectHash = require('object-hash');
|
2 | const {memoizeNonPrimitives} = require('./memoize');
|
3 | const _ = require('lodash');
|
4 |
|
5 | let strHash = {};
|
6 | const hashString = str => {
|
7 | if (!strHash[str]) {
|
8 | strHash[str] = objectHash(str);
|
9 | }
|
10 | const res = strHash[str];
|
11 | return res;
|
12 | };
|
13 |
|
14 | const clearHashStrings = () => {
|
15 | strHash = {};
|
16 | }
|
17 |
|
18 | const exprHash = memoizeNonPrimitives(
|
19 | obj => {
|
20 |
|
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 |
|
35 | module.exports = {exprHash, hashString, clearHashStrings};
|