Last active
November 21, 2016 14:36
-
-
Save naveed-fida/8f3d07968d212462935f25813ddbbb92 to your computer and use it in GitHub Desktop.
An implementation of JSON.stringify
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 stringifyObj(obj) { | |
let toStr = Object.prototype.toString; | |
if(toStr.call(obj) == "[object String]") { | |
return "\"" + String(obj) + "\""; | |
} else if (toStr.call(obj) == "[object Number]") { | |
return String(obj); | |
} else if(toStr.call(obj) == "[object Array]") { | |
let resultStr = "[" | |
for (let i = 0; i < obj.length; i++) { | |
resultStr += stringifyObj(obj[i]); | |
if (i === obj.length - 1) continue; | |
resultStr += "," | |
} | |
return retStr + "]"; | |
} else if(toStr.call(obj) == "[object Object]") { | |
obj = hashify(obj); | |
let keys = Object.keys(obj), | |
resultStr = "{"; | |
for (let i = 0; i < keys.length; i++) { | |
resultStr += "\"" + keys[i] + "\":" + stringifyObj(obj[keys[i]]); | |
if (i == keys.length - 1) continue; | |
resultStr += ","; | |
} | |
return resultStr + "}" | |
} | |
function hashify(obj) { | |
let resultObj = {}, | |
keys = Object.keys(obj); | |
for (let i=0; i < keys.length; i++) { | |
if (typeof obj[keys[i]] !== "function") { | |
resultObj[keys[i]] = obj[keys[i]]; | |
} | |
} | |
return resultObj; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment