You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

132 lines
2.3 KiB

7 years ago
  1. // Load modules
  2. // Declare internals
  3. var internals = {};
  4. exports.arrayToObject = function (source) {
  5. var obj = {};
  6. for (var i = 0, il = source.length; i < il; ++i) {
  7. if (typeof source[i] !== 'undefined') {
  8. obj[i] = source[i];
  9. }
  10. }
  11. return obj;
  12. };
  13. exports.merge = function (target, source) {
  14. if (!source) {
  15. return target;
  16. }
  17. if (typeof source !== 'object') {
  18. if (Array.isArray(target)) {
  19. target.push(source);
  20. }
  21. else {
  22. target[source] = true;
  23. }
  24. return target;
  25. }
  26. if (typeof target !== 'object') {
  27. target = [target].concat(source);
  28. return target;
  29. }
  30. if (Array.isArray(target) &&
  31. !Array.isArray(source)) {
  32. target = exports.arrayToObject(target);
  33. }
  34. var keys = Object.keys(source);
  35. for (var k = 0, kl = keys.length; k < kl; ++k) {
  36. var key = keys[k];
  37. var value = source[key];
  38. if (!target[key]) {
  39. target[key] = value;
  40. }
  41. else {
  42. target[key] = exports.merge(target[key], value);
  43. }
  44. }
  45. return target;
  46. };
  47. exports.decode = function (str) {
  48. try {
  49. return decodeURIComponent(str.replace(/\+/g, ' '));
  50. } catch (e) {
  51. return str;
  52. }
  53. };
  54. exports.compact = function (obj, refs) {
  55. if (typeof obj !== 'object' ||
  56. obj === null) {
  57. return obj;
  58. }
  59. refs = refs || [];
  60. var lookup = refs.indexOf(obj);
  61. if (lookup !== -1) {
  62. return refs[lookup];
  63. }
  64. refs.push(obj);
  65. if (Array.isArray(obj)) {
  66. var compacted = [];
  67. for (var i = 0, il = obj.length; i < il; ++i) {
  68. if (typeof obj[i] !== 'undefined') {
  69. compacted.push(obj[i]);
  70. }
  71. }
  72. return compacted;
  73. }
  74. var keys = Object.keys(obj);
  75. for (i = 0, il = keys.length; i < il; ++i) {
  76. var key = keys[i];
  77. obj[key] = exports.compact(obj[key], refs);
  78. }
  79. return obj;
  80. };
  81. exports.isRegExp = function (obj) {
  82. return Object.prototype.toString.call(obj) === '[object RegExp]';
  83. };
  84. exports.isBuffer = function (obj) {
  85. if (obj === null ||
  86. typeof obj === 'undefined') {
  87. return false;
  88. }
  89. return !!(obj.constructor &&
  90. obj.constructor.isBuffer &&
  91. obj.constructor.isBuffer(obj));
  92. };