Guest User

Untitled

a guest
Dec 11th, 2018
72
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.06 KB | None | 0 0
  1. <script id="jsbin-javascript">
  2. /*
  3. * Exercise, write your own implementation of JSON.stringify
  4. * It has to support:
  5. * - strings
  6. * - numbers
  7. * - arrays (of mixed elements)
  8. * - objects
  9. * - nested objects
  10. */
  11.  
  12. module.exports = function JSONStringify(obj)
  13. {
  14. let returnStr = "";
  15. let templateStr = ""
  16.  
  17. if (Array.isArray(obj))
  18. {
  19. templateStr = "[{{STRING}}]";
  20.  
  21. for (let i = 0; i < obj.length; i++)
  22. {
  23. returnStr += JSONStringify(obj[i]) + ",";
  24. }
  25. returnStr = returnStr.substr(0, returnStr.length - 1);
  26. return templateStr.replace("{{STRING}}", returnStr);
  27. }
  28. else if (typeof obj === "object")
  29. {
  30. templateStr = "{{{STRING}}}";
  31. for (let key in obj)
  32. {
  33. returnStr += "\"" + key + "\":" + JSONStringify(obj[key]) + ",";
  34. }
  35. returnStr = returnStr.substr(0, returnStr.length - 1);
  36. return templateStr.replace("{{STRING}}", returnStr);
  37. }
  38. else if (typeof obj === "string")
  39. {
  40. return "\"" + obj + "\"";
  41. }
  42. else if (typeof obj === "number")
  43. {
  44. return obj.toString();
  45. }
  46. return returnStr;
  47. };
  48. </script>
  49.  
  50.  
  51. <script id="jsbin-source-javascript" type="text/javascript">/*
  52. * Exercise, write your own implementation of JSON.stringify
  53. * It has to support:
  54. * - strings
  55. * - numbers
  56. * - arrays (of mixed elements)
  57. * - objects
  58. * - nested objects
  59. */
  60.  
  61. module.exports = function JSONStringify(obj)
  62. {
  63. let returnStr = "";
  64. let templateStr = ""
  65.  
  66. if (Array.isArray(obj))
  67. {
  68. templateStr = "[{{STRING}}]";
  69.  
  70. for (let i = 0; i < obj.length; i++)
  71. {
  72. returnStr += JSONStringify(obj[i]) + ",";
  73. }
  74. returnStr = returnStr.substr(0, returnStr.length - 1);
  75. return templateStr.replace("{{STRING}}", returnStr);
  76. }
  77. else if (typeof obj === "object")
  78. {
  79. templateStr = "{{{STRING}}}";
  80. for (let key in obj)
  81. {
  82. returnStr += "\"" + key + "\":" + JSONStringify(obj[key]) + ",";
  83. }
  84. returnStr = returnStr.substr(0, returnStr.length - 1);
  85. return templateStr.replace("{{STRING}}", returnStr);
  86. }
  87. else if (typeof obj === "string")
  88. {
  89. return "\"" + obj + "\"";
  90. }
  91. else if (typeof obj === "number")
  92. {
  93. return obj.toString();
  94. }
  95. return returnStr;
  96. };
  97. </script>
Add Comment
Please, Sign In to add comment