Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #2 from cyberphone/dev
Dev
- Loading branch information
Showing
3 changed files
with
315 additions
and
37 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,72 @@ | ||
// Sample showing how a naive use of JCS will fail | ||
'use strict'; | ||
var canonicalize = function(object) { | ||
|
||
var buffer = ''; | ||
serialize(object); | ||
return buffer; | ||
|
||
function serialize(object) { | ||
if (object === null || typeof object !== 'object' || | ||
object.toJSON != null) { | ||
///////////////////////////////////////////////// | ||
// Primitive type or toJSON - Use ES6/JSON // | ||
///////////////////////////////////////////////// | ||
buffer += JSON.stringify(object); | ||
|
||
} else if (Array.isArray(object)) { | ||
///////////////////////////////////////////////// | ||
// Array - Maintain element order // | ||
///////////////////////////////////////////////// | ||
buffer += '['; | ||
let next = false; | ||
object.forEach((element) => { | ||
if (next) { | ||
buffer += ','; | ||
} | ||
next = true; | ||
///////////////////////////////////////// | ||
// Array element - Recursive expansion // | ||
///////////////////////////////////////// | ||
serialize(element); | ||
}); | ||
buffer += ']'; | ||
|
||
} else { | ||
///////////////////////////////////////////////// | ||
// Object - Sort properties before serializing // | ||
///////////////////////////////////////////////// | ||
buffer += '{'; | ||
let next = false; | ||
Object.keys(object).sort().forEach((property) => { | ||
if (next) { | ||
buffer += ','; | ||
} | ||
next = true; | ||
/////////////////////////////////////////////// | ||
// Property names are strings - Use ES6/JSON // | ||
/////////////////////////////////////////////// | ||
buffer += JSON.stringify(property); | ||
buffer += ':'; | ||
////////////////////////////////////////// | ||
// Property value - Recursive expansion // | ||
////////////////////////////////////////// | ||
serialize(object[property]); | ||
}); | ||
buffer += '}'; | ||
} | ||
} | ||
}; | ||
|
||
const jstring = | ||
'{"time": "2019-01-28T07:45:10Z", "big": "055", "val": 3.5}'; | ||
|
||
BigInt.prototype.toJSON = function () { | ||
return this.toString(); | ||
}; | ||
|
||
var object = JSON.parse(jstring, | ||
(k,v) => k == 'time' ? new Date(v) : k == 'big' ? BigInt(v) : v | ||
); | ||
|
||
console.log(canonicalize(object)); |
Oops, something went wrong.