This repository was archived by the owner on Oct 1, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 95
Expand file tree
/
Copy pathdigest-for-object.js
More file actions
64 lines (52 loc) · 1.49 KB
/
digest-for-object.js
File metadata and controls
64 lines (52 loc) · 1.49 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
import crypto from 'crypto';
function updateDigestForJsonValue(shasum, value) {
// Implementation is similar to that of pretty-printing a JSON object, except:
// * Strings are not escaped.
// * No effort is made to avoid trailing commas.
// These shortcuts should not affect the correctness of this function.
const type = typeof(value);
if (type === 'string') {
shasum.update('"', 'utf8');
shasum.update(value, 'utf8');
shasum.update('"', 'utf8');
return;
}
if (type === 'boolean' || type === 'number') {
shasum.update(value.toString(), 'utf8');
return;
}
if (!value) {
shasum.update('null', 'utf8');
return;
}
if (Array.isArray(value)) {
shasum.update('[', 'utf8');
for (let i=0; i < value.length; i++) {
updateDigestForJsonValue(shasum, value[i]);
shasum.update(',', 'utf8');
}
shasum.update(']', 'utf8');
return;
}
// value must be an object: be sure to sort the keys.
let keys = Object.keys(value);
keys.sort();
shasum.update('{', 'utf8');
for (let i=0; i < keys.length; i++) {
updateDigestForJsonValue(shasum, keys[i]);
shasum.update(': ', 'utf8');
updateDigestForJsonValue(shasum, value[keys[i]]);
shasum.update(',', 'utf8');
}
shasum.update('}', 'utf8');
}
/**
* Creates a hash from a JS object
*
* @private
*/
export default function createDigestForObject(obj) {
let sha1 = crypto.createHash('sha1');
updateDigestForJsonValue(sha1, obj);
return sha1.digest('hex');
}