Skip to content

Instantly share code, notes, and snippets.

@naveed-fida
Last active November 21, 2016 14:36
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 naveed-fida/8f3d07968d212462935f25813ddbbb92 to your computer and use it in GitHub Desktop.
Save naveed-fida/8f3d07968d212462935f25813ddbbb92 to your computer and use it in GitHub Desktop.
An implementation of JSON.stringify
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