Skip to content

Instantly share code, notes, and snippets.

@Luke-Rogerson
Last active September 1, 2018 18:29
Show Gist options
  • Save Luke-Rogerson/4dea3c999ecc13d5b4af4d06ec2163bf to your computer and use it in GitHub Desktop.
Save Luke-Rogerson/4dea3c999ecc13d5b4af4d06ec2163bf to your computer and use it in GitHub Desktop.
function stringifier (input) {
if (typeof input === 'string') { //test for string, empty string
return '"' + input + '"';
}
if (typeof input === 'function' || typeof input === 'undefined') { // test for function or undefined
return undefined;
}
if (input === null) { // test for null
return 'null';
}
if (Array.isArray(input)) { // test for arrays and nested arrays
let stringifiedArray = [];
for (let element = 0; element < input.length; element++) if (input.hasOwnProperty(element)) {
if (typeof input[element] === 'function' || input[element] === undefined) {
stringifiedArray.push('null');
}
else {
stringifiedArray.push(stringifier(input[element]));
}
}
let output = '[' + stringifiedArray.join(',') + ']';
return output;
}
if (typeof input === 'object') { // test for objects and nested objects
let stringifiedObjectArray = [];
for (let value in input) if (input.hasOwnProperty(value)) {
if (input[value] !== undefined && typeof input[value] !== 'function') {
stringifiedObjectArray.push(stringifier(value) + ':' + stringifier(input[value]));
}
}
let output = '{' + stringifiedObjectArray.join(',') + '}';
return output;
}
return input + ''; //test for numbers
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment