Skip to content

Instantly share code, notes, and snippets.

@Jiert
Created February 2, 2017 21:12
Show Gist options
  • Save Jiert/3d3f62e63f1597ebb0038f2f1c98b905 to your computer and use it in GitHub Desktop.
Save Jiert/3d3f62e63f1597ebb0038f2f1c98b905 to your computer and use it in GitHub Desktop.
Stringify
// Implement JSON.stringify
var example = {
"array": [1, 2, 3],
"number": 123,
"object": {
"a": "b",
"c": "d",
"e": "f"
},
"string": "Hello World"
}
var stringify = function(obj) {
var output = "";
if (typeof(obj) === 'number') {
output = output.concat(obj)
} else if (typeof(obj) === 'string') {
output = output.concat('"', obj, '"')
} else if (Array.isArray(obj)) {
output = output.concat('[', obj.map(stringify), ']')
} else if (typeof(obj) === 'object') {
var entries = Object.entries(obj);
output = output.concat('{', entries.map(function(entry) {
return "".concat('"', entry[0], '":', stringify(entry[1]))
}), '}')
}
return output;
}
var output = stringify(example);
console.log(output)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment