-
Notifications
You must be signed in to change notification settings - Fork 3
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
4 changed files
with
44 additions
and
25 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,27 +1,42 @@ | ||
const MD5 = require('md5.js') | ||
const stringify = require('json-stable-stringify') | ||
|
||
const ERROR_UNSAFE_NUMBER = 'ERROR_UNSAFE_NUMBER' | ||
|
||
class CrossHashError extends Error { | ||
constructor(message) { | ||
super(message) | ||
this.name = CrossHashError.name | ||
} | ||
} | ||
|
||
const crosshash = (obj) => { | ||
return hashString(crossjson(obj)) | ||
return md5(crossjson(obj)) | ||
} | ||
|
||
const crossjson = (obj) => { | ||
return stringify(obj, {replacer: safeIntegerReplacer}) | ||
return stringify(obj, {replacer: replacer}) | ||
} | ||
|
||
const hashString = (string) => { | ||
const md5 = (string) => { | ||
return new MD5().update(string).digest('hex') | ||
} | ||
|
||
const safeIntegerReplacer = (key, value) => { | ||
if (typeof value === 'number' && !Number.isSafeInteger(value)) { | ||
throw new Error(`ERROR_UNSAFE_NUMBER: ${value}`) | ||
const replacer = (key, value) => { | ||
if (typeof value === 'number') { | ||
validateNumber(value) | ||
} | ||
return value | ||
} | ||
|
||
const validateNumber = (value) => { | ||
if (!Number.isSafeInteger(value)) { | ||
throw new CrossHashError(`${ERROR_UNSAFE_NUMBER}: ${value}`) | ||
} | ||
} | ||
|
||
module.exports = { | ||
crosshash, | ||
crossjson, | ||
CrossHashError, | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters