forked from byteball/ocore
-
Notifications
You must be signed in to change notification settings - Fork 0
/
string_utils.js
59 lines (53 loc) · 2.15 KB
/
string_utils.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
55
56
57
/*jslint node: true */
"use strict";
const STRING_JOIN_CHAR = "\x00";
/**
* Converts the argument into a string by mapping data types to a prefixed string and concatenating all fields together.
* @param obj the value to be converted into a string
* @returns {string} the string version of the value
*/
function getSourceString(obj) {
var arrComponents = [];
function extractComponents(variable){
if (variable === null)
throw Error("null value in "+JSON.stringify(obj));
switch (typeof variable){
case "string":
arrComponents.push("s", variable);
break;
case "number":
arrComponents.push("n", variable.toString());
break;
case "boolean":
arrComponents.push("b", variable.toString());
break;
case "object":
if (Array.isArray(variable)){
if (variable.length === 0)
throw Error("empty array in "+JSON.stringify(obj));
arrComponents.push('[');
for (var i=0; i<variable.length; i++)
extractComponents(variable[i]);
arrComponents.push(']');
}
else{
var keys = Object.keys(variable).sort();
if (keys.length === 0)
throw Error("empty object in "+JSON.stringify(obj));
keys.forEach(function(key){
if (typeof variable[key] === "undefined")
throw Error("undefined at "+key+" of "+JSON.stringify(obj));
arrComponents.push(key);
extractComponents(variable[key]);
});
}
break;
default:
throw Error("hash: unknown type="+(typeof variable)+" of "+variable+", object: "+JSON.stringify(obj));
}
}
extractComponents(obj);
return arrComponents.join(STRING_JOIN_CHAR);
}
exports.STRING_JOIN_CHAR = STRING_JOIN_CHAR; // for tests
exports.getSourceString = getSourceString;