Created
July 18, 2018 10:14
-
-
Save Gergling/52b4f90a6afc3b818d31cab6e7ad103b to your computer and use it in GitHub Desktop.
This file contains hidden or 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
function stringifyExplicitObject(subject) { | |
return '{' + Object.entries(subject).map(function (entry) { | |
return entry[0] + ':' + stringify(entry[1]); | |
}).join(',') + '}'; | |
} | |
function stringifyArray(subject) { | |
return '[' + subject.map(function (element) { | |
return stringify(element); | |
}).join(',') + ']'; | |
} | |
function stringifyObject(subject) { | |
// Check if the subject is an array. If so... | |
return subject.constructor === [].constructor | |
// Treat it as an array. Otherwise... | |
? stringifyArray(subject) | |
// Treat it as an explicit object. | |
: stringifyExplicitObject(subject); | |
} | |
function stringify (subject) { | |
// Check if the subject is an object. If so... | |
return typeof subject === 'object' | |
// Treat it as an object. Otherwise... | |
? stringifyObject(subject) | |
// Treat it as a primitive value. | |
: '"' + subject + '"'; | |
} | |
module.exports = stringify; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment