serialize.js 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. "use strict";
  2. var toArray = require("./to-array")
  3. , isDate = require("../date/is-date")
  4. , isValue = require("../object/is-value")
  5. , isRegExp = require("../reg-exp/is-reg-exp");
  6. var isArray = Array.isArray
  7. , stringify = JSON.stringify
  8. , objHasOwnProperty = Object.prototype.hasOwnProperty;
  9. var keyValueToString = function (value, key) {
  10. return stringify(key) + ":" + module.exports(value);
  11. };
  12. var sparseMap = function (arr) {
  13. var i, length = arr.length, result = new Array(length);
  14. for (i = 0; i < length; ++i) {
  15. if (!objHasOwnProperty.call(arr, i)) continue;
  16. result[i] = module.exports(arr[i]);
  17. }
  18. return result;
  19. };
  20. module.exports = function (obj) {
  21. if (!isValue(obj)) return String(obj);
  22. switch (typeof obj) {
  23. case "string":
  24. return stringify(obj);
  25. case "number":
  26. case "boolean":
  27. case "function":
  28. return String(obj);
  29. case "object":
  30. if (isArray(obj)) return "[" + sparseMap(obj) + "]";
  31. if (isRegExp(obj)) return String(obj);
  32. if (isDate(obj)) return "new Date(" + obj.valueOf() + ")";
  33. return "{" + toArray(obj, keyValueToString) + "}";
  34. default:
  35. throw new TypeError("Serialization of " + String(obj) + "is unsupported");
  36. }
  37. };