-
Notifications
You must be signed in to change notification settings - Fork 9
/
index.js
54 lines (48 loc) · 1.34 KB
/
index.js
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
'use strict'
const crypto = require('crypto')
function _serialize(obj) {
if (Array.isArray(obj)) {
return `[${obj.map(el => _serialize(el)).join(',')}]`
} else if (typeof obj === 'object' && obj !== null) {
let acc = ''
const keys = Object.keys(obj).sort()
acc += `{${JSON.stringify(keys)}`
for (let i = 0; i < keys.length; i++) {
acc += `${_serialize(obj[keys[i]])},`
}
return `${acc}}`
}
return `${JSON.stringify(obj)}`
}
/**
* Serializes a JSON object (not any random JS object).
*
* It should be noted that JS objects can have members of
* specific type (e.g. function), that are not supported
* by JSON.
*
* @param {Object} obj JSON object
* @returns {String} stringified JSON object.
*/
function serialize (obj) {
return _serialize(obj, '')
}
/**
* Creates hash of given JSON object.
*
* @param {Object} obj JSON object
* @param {String} hashAlgorithm hash algorithm (e.g. SHA256)
* @param {String} encoding hash encoding (e.g. base64) or none for buffer
* @see #serialize
*/
function digest (obj, hashAlgorithm, encoding) {
const hash = crypto.createHash(hashAlgorithm)
return hash.update(serialize(obj)).digest(encoding)
}
module.exports = {
stringify: () => {
throw new Error('"stringify()" is deprecated, use "serialize()" instead!')
},
serialize: serialize,
digest: digest
}