Skip to content

Instantly share code, notes, and snippets.

@Gergling
Created July 18, 2018 10:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Gergling/52b4f90a6afc3b818d31cab6e7ad103b to your computer and use it in GitHub Desktop.
Save Gergling/52b4f90a6afc3b818d31cab6e7ad103b to your computer and use it in GitHub Desktop.
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