serialize.js 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. var objToString = Object.prototype.toString;
  2. var objKeys = Object.getOwnPropertyNames;
  3. /**
  4. * A custom Babel options serializer
  5. *
  6. * Intentional deviation from JSON.stringify:
  7. * 1. Object properties are sorted before seralizing
  8. * 2. The output is NOT a valid JSON: e.g.
  9. * The output does not enquote strings, which means a JSON-like string '{"a":1}'
  10. * will share the same result with an JS object { a: 1 }. This is not an issue
  11. * for Babel options, but it can not be used for general serialization purpose
  12. * 3. Only 20% slower than the native JSON.stringify on V8
  13. *
  14. * This function is a fork from https://github.com/nickyout/fast-stable-stringify
  15. * @param {*} val Babel options
  16. * @param {*} isArrayProp
  17. * @returns serialized Babel options
  18. */
  19. function serialize(val, isArrayProp) {
  20. var i, max, str, keys, key, propVal, toStr;
  21. if (val === true) {
  22. return "!0";
  23. }
  24. if (val === false) {
  25. return "!1";
  26. }
  27. switch (typeof val) {
  28. case "object":
  29. if (val === null) {
  30. return null;
  31. } else if (val.toJSON && typeof val.toJSON === "function") {
  32. return serialize(val.toJSON(), isArrayProp);
  33. } else {
  34. toStr = objToString.call(val);
  35. if (toStr === "[object Array]") {
  36. str = "[";
  37. max = val.length - 1;
  38. for (i = 0; i < max; i++) {
  39. str += serialize(val[i], true) + ",";
  40. }
  41. if (max > -1) {
  42. str += serialize(val[i], true);
  43. }
  44. return str + "]";
  45. } else if (toStr === "[object Object]") {
  46. // only object is left
  47. keys = objKeys(val).sort();
  48. max = keys.length;
  49. str = "{";
  50. i = 0;
  51. while (i < max) {
  52. key = keys[i];
  53. propVal = serialize(val[key], false);
  54. if (propVal !== undefined) {
  55. if (str) {
  56. str += ",";
  57. }
  58. str += '"' + key + '":' + propVal;
  59. }
  60. i++;
  61. }
  62. return str + "}";
  63. } else {
  64. return JSON.stringify(val);
  65. }
  66. }
  67. case "function":
  68. case "undefined":
  69. return isArrayProp ? null : undefined;
  70. case "string":
  71. return val;
  72. default:
  73. return isFinite(val) ? val : null;
  74. }
  75. }
  76. module.exports = function (val) {
  77. var returnVal = serialize(val, false);
  78. if (returnVal !== undefined) {
  79. return "" + returnVal;
  80. }
  81. };