source: imaps-frontend/node_modules/fastest-stable-stringify/index.js

main
Last change on this file was d565449, checked in by stefan toskovski <stefantoska84@…>, 4 weeks ago

Update repo after prototype presentation

  • Property mode set to 100644
File size: 1.6 KB
Line 
1'use strict';
2
3var keyList = Object.keys;
4var native_stringify = JSON.stringify;
5
6function stringify(val, allowUndefined) {
7 var i, max, str, keys, key, propVal, tipeof;
8
9 tipeof = typeof val;
10
11 if (tipeof === 'string') return native_stringify(val);
12 if (val === true) return 'true';
13 if (val === false) return 'false';
14 if (val === null) return 'null';
15
16 if (val instanceof Array) {
17 str = '[';
18 max = val.length - 1;
19 for(i = 0; i < max; i++)
20 str += stringify(val[i], false) + ',';
21 if (max > -1) {
22 str += stringify(val[i], false);
23 }
24
25 return str + ']';
26 }
27
28 if (val instanceof Object) {
29 if (typeof val.toJSON === 'function')
30 return stringify(val.toJSON(), allowUndefined);
31
32 // only object is left
33 keys = keyList(val).sort();
34 max = keys.length;
35 str = '';
36 i = 0;
37 while (i < max) {
38 key = keys[i];
39 propVal = stringify(val[key], true);
40 if (propVal !== undefined) {
41 if (i && str !== '') { //if the string is empty, don't add comma to avoid the json to become invalid.
42 str += ',';
43 }
44 str += native_stringify(key) + ':' + propVal;
45 }
46 i++;
47 }
48 return '{' + str + '}';
49 }
50
51 switch (tipeof) {
52 case 'function':
53 case 'undefined':
54 return allowUndefined ? undefined : null;
55 default:
56 return isFinite(val) ? val : null;
57 }
58}
59
60module.exports = function(obj) { return '' + stringify(obj, false); };
Note: See TracBrowser for help on using the repository browser.