serialize.js 1.0 KB

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