Last active
November 12, 2015 14:29
-
-
Save k10526/8958311137486ec8d5c2 to your computer and use it in GitHub Desktop.
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
function stringify(o){ | |
var visited = []; | |
var q = [{type: typeof o, target: o}]; | |
var res = ''; | |
var t; | |
while(t=q.shift()){ | |
var tar = t.target; | |
if(!tar){ | |
res += 'null'; | |
continue; | |
} | |
switch (t.type){ | |
case 'object': | |
if(visited.indexOf(tar)!==-1){ | |
if(t.pos==null) | |
throw new Error(); | |
}else { | |
visited.push(tar); | |
} | |
t.pos==null&&(t.pos=-1); | |
var pos = t.pos; | |
var key; | |
if(Array.isArray(tar)){ | |
if(pos===-1){ | |
res += '['; | |
t.pos++; | |
q.unshift(t); | |
continue; | |
} | |
if(pos === tar.length){ | |
res += ']'; | |
t.pos =-1; | |
continue; | |
} | |
key = pos; | |
res += pos?',':''; | |
}else { | |
var keys = t.keys||(t.keys = Object.keys(tar)); | |
if(pos===-1){ | |
res += '{'; | |
t.pos++; | |
q.unshift(t); | |
continue; | |
} | |
if(pos === keys.length){ | |
res += '}'; | |
t.pos = -1; | |
continue; | |
} | |
key = keys[pos]; | |
res += (pos?',':'')+key+':'; | |
} | |
t.pos++; | |
q.unshift(t); | |
q.unshift({type: typeof t.target[key], target: t.target[key]}); | |
break; | |
case 'number': | |
res += tar; | |
break; | |
case 'string': | |
res += '"'+tar.replace(/"/g,'\\"')+'"'; | |
break; | |
default: | |
res += 'null'; | |
break; | |
} | |
} | |
return res; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment