Tim van der Lippe | fdbd42e | 2020-04-07 15:14:36 +0100 | [diff] [blame^] | 1 | /** |
| 2 | * utilities for hashing config objects. |
| 3 | * basically iteratively updates hash with a JSON-like format |
| 4 | */ |
| 5 | 'use strict' |
| 6 | exports.__esModule = true |
| 7 | |
| 8 | const createHash = require('crypto').createHash |
| 9 | |
| 10 | const stringify = JSON.stringify |
| 11 | |
| 12 | function 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 | } |
| 25 | exports.default = hashify |
| 26 | |
| 27 | function 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 | } |
| 39 | hashify.array = hashArray |
| 40 | exports.hashArray = hashArray |
| 41 | |
| 42 | function 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 | } |
| 56 | hashify.object = hashObject |
| 57 | exports.hashObject = hashObject |
| 58 | |
| 59 | |