Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <script id="jsbin-javascript">
- /*
- * Exercise, write your own implementation of JSON.stringify
- * It has to support:
- * - strings
- * - numbers
- * - arrays (of mixed elements)
- * - objects
- * - nested objects
- */
- module.exports = function JSONStringify(obj)
- {
- let returnStr = "";
- let templateStr = ""
- if (Array.isArray(obj))
- {
- templateStr = "[{{STRING}}]";
- for (let i = 0; i < obj.length; i++)
- {
- returnStr += JSONStringify(obj[i]) + ",";
- }
- returnStr = returnStr.substr(0, returnStr.length - 1);
- return templateStr.replace("{{STRING}}", returnStr);
- }
- else if (typeof obj === "object")
- {
- templateStr = "{{{STRING}}}";
- for (let key in obj)
- {
- returnStr += "\"" + key + "\":" + JSONStringify(obj[key]) + ",";
- }
- returnStr = returnStr.substr(0, returnStr.length - 1);
- return templateStr.replace("{{STRING}}", returnStr);
- }
- else if (typeof obj === "string")
- {
- return "\"" + obj + "\"";
- }
- else if (typeof obj === "number")
- {
- return obj.toString();
- }
- return returnStr;
- };
- </script>
- <script id="jsbin-source-javascript" type="text/javascript">/*
- * Exercise, write your own implementation of JSON.stringify
- * It has to support:
- * - strings
- * - numbers
- * - arrays (of mixed elements)
- * - objects
- * - nested objects
- */
- module.exports = function JSONStringify(obj)
- {
- let returnStr = "";
- let templateStr = ""
- if (Array.isArray(obj))
- {
- templateStr = "[{{STRING}}]";
- for (let i = 0; i < obj.length; i++)
- {
- returnStr += JSONStringify(obj[i]) + ",";
- }
- returnStr = returnStr.substr(0, returnStr.length - 1);
- return templateStr.replace("{{STRING}}", returnStr);
- }
- else if (typeof obj === "object")
- {
- templateStr = "{{{STRING}}}";
- for (let key in obj)
- {
- returnStr += "\"" + key + "\":" + JSONStringify(obj[key]) + ",";
- }
- returnStr = returnStr.substr(0, returnStr.length - 1);
- return templateStr.replace("{{STRING}}", returnStr);
- }
- else if (typeof obj === "string")
- {
- return "\"" + obj + "\"";
- }
- else if (typeof obj === "number")
- {
- return obj.toString();
- }
- return returnStr;
- };
- </script>
Add Comment
Please, Sign In to add comment