Skip to content

Instantly share code, notes, and snippets.

@SerpentChris
Last active May 13, 2017 02:44
Show Gist options
  • Save SerpentChris/0df9f0be9e4ced2d6dec6a773a6c6b21 to your computer and use it in GitHub Desktop.
Save SerpentChris/0df9f0be9e4ced2d6dec6a773a6c6b21 to your computer and use it in GitHub Desktop.
A simple, recursive stringify implementation
function escape(string){
var chars = []
for(var i = 0 ; i < string.length; i++){
var c = string.charAt(i)
switch(c){
case '\n':
chars.push('\\n')
break
case '\t':
chars.push('\\t')
break
case '\'':
chars.push('\\\'')
break
case '"':
chars.push('\\\"')
break
default:
chars.push(c)
}
}
return chars.join('')
}
function stringify(obj){
if (obj === null){
return 'null'
} else if ((typeof obj == 'number') || (typeof obj == 'boolean')){
return obj.toString()
} else if (typeof obj == 'string'){
return '"' + escape(obj) + '"'
} else if (Array.isArray(obj)){
return '[' + obj.map(stringify).join(', ') + ']'
} else if (typeof obj == 'object'){
return '{' + Object.keys(obj).map(function(k){return stringify(k) + ': ' + stringify(obj[k])}).join(', ') + '}'
}
}
function test(){
console.log(stringify({}))
console.log(stringify(true))
console.log(stringify('foo'))
console.log(stringify('the quick brown fox jumps\n\tover the lazy dog'))
console.log(stringify([1, 'false', false]))
console.log(stringify({x: 5}))
}
test()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment