Skip to content

Instantly share code, notes, and snippets.

@andrew8088
Last active August 23, 2022 07:54
Show Gist options
  • Save andrew8088/6f53af9579266d5c62c8 to your computer and use it in GitHub Desktop.
Save andrew8088/6f53af9579266d5c62c8 to your computer and use it in GitHub Desktop.
A simple implementation of JSON.stringify; covers every case I could think of
function stringify(obj) {
if (typeof obj !== 'object' || obj === null || obj instanceof Array) {
return value(obj);
}
return '{' + Object.keys(obj).map(function (k) {
return (typeof obj[k] === 'function') ? null : '"' + k + '":' + value(obj[k]);
}).filter(function (i) { return i; }) + '}';
}
function value(val) {
switch(typeof val) {
case 'string':
return '"' + val.replace(/\\/g, '\\\\').replace('"', '\\"') + '"';
case 'number':
case 'boolean':
return '' + val;
case 'function':
return 'null';
case 'object':
if (val instanceof Date) return '"' + val.toISOString() + '"';
if (val instanceof Array) return '[' + val.map(value).join(',') + ']';
if (val === null) return 'null';
return stringify(val);
}
}
var assert = require('assert');
describe('stringify', function () {
function check(o) {
return function () {
assert.equal(stringify(o), JSON.stringify(o));
};
}
it("string", check('andrew'));
it('string with special chars', check('this"is a \\test'));
it("number", check(10));
it("true", check(true));
it("false", check(false));
it("null", check(null));
it("array", check(['one', 'two', 1, { name: 'andrew'}]));
it("empty object", check({}));
it("string prop", check({ name: "andrew" }));
it("number prop", check({ name: "andrew", age: 24 }));
it("boolean prop", check({ name: "andrew", age: 24, married: false, single: true }));
it("date prop", check({ name: "andrew", age: 24, married: false, single: true, date: new Date() }));
it("array prop of strings", check({ array: ['one', 'two'] }));
it("array prop of differing values", check({ array: ['one', 2, false, null, { value: 'five', or: 2}] }));
it("null prop", check({ array: ['one', 'two'], nothing: null }));
it("object prop", check({ name: 'andrew', address: { streetAddress: '21st street', city: 'New York', state: 'NY'}}));
it("functions", check({ name: 'andrew', doSomething: function () {} }));
it("functions in array property", check({ name: 'andrew', doSomething: [function () {}] }));
});
@siddharth-sunchu
Copy link

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment