serialize.js 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839
  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) { return stringify(key) + ":" + exports(value); };
  10. var sparseMap = function (arr) {
  11. var i, length = arr.length, result = new Array(length);
  12. for (i = 0; i < length; ++i) {
  13. if (!objHasOwnProperty.call(arr, i)) continue;
  14. result[i] = exports(arr[i]);
  15. }
  16. return result;
  17. };
  18. module.exports = exports = function (obj) {
  19. if (!isValue(obj)) return String(obj);
  20. switch (typeof obj) {
  21. case "string":
  22. return stringify(obj);
  23. case "number":
  24. case "boolean":
  25. case "function":
  26. return String(obj);
  27. case "object":
  28. if (isArray(obj)) return "[" + sparseMap(obj) + "]";
  29. if (isRegExp(obj)) return String(obj);
  30. if (isDate(obj)) return "new Date(" + obj.valueOf() + ")";
  31. return "{" + toArray(obj, keyValueToString) + "}";
  32. default:
  33. throw new TypeError("Serialization of " + String(obj) + "is unsupported");
  34. }
  35. };