Created
February 2, 2017 21:12
-
-
Save Jiert/3d3f62e63f1597ebb0038f2f1c98b905 to your computer and use it in GitHub Desktop.
Stringify
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
// 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