UNPKG

1.18 kBJavaScriptView Raw
1/**
2 * utilities for hashing config objects.
3 * basically iteratively updates hash with a JSON-like format
4 */
5'use strict'
6exports.__esModule = true
7
8const createHash = require('crypto').createHash
9
10const stringify = JSON.stringify
11
12function hashify(value, hash) {
13 if (!hash) hash = createHash('sha256')
14
15 if (value instanceof Array) {
16 hashArray(value, hash)
17 } else if (value instanceof Object) {
18 hashObject(value, hash)
19 } else {
20 hash.update(stringify(value) || 'undefined')
21 }
22
23 return hash
24}
25exports.default = hashify
26
27function hashArray(array, hash) {
28 if (!hash) hash = createHash('sha256')
29
30 hash.update('[')
31 for (let i = 0; i < array.length; i++) {
32 hashify(array[i], hash)
33 hash.update(',')
34 }
35 hash.update(']')
36
37 return hash
38}
39hashify.array = hashArray
40exports.hashArray = hashArray
41
42function hashObject(object, hash) {
43 if (!hash) hash = createHash('sha256')
44
45 hash.update('{')
46 Object.keys(object).sort().forEach(key => {
47 hash.update(stringify(key))
48 hash.update(':')
49 hashify(object[key], hash)
50 hash.update(',')
51 })
52 hash.update('}')
53
54 return hash
55}
56hashify.object = hashObject
57exports.hashObject = hashObject
58
59