utils.js 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. "use strict";
  2. const { toString } = Object.prototype;
  3. function isArray(val) {
  4. return toString.call(val) === "[object Array]";
  5. }
  6. function isObject(val) {
  7. return val !== null && typeof val === "object";
  8. }
  9. function isDate(val) {
  10. return toString.call(val) === "[object Date]";
  11. }
  12. function isURLSearchParams(val) {
  13. return typeof URLSearchParams !== "undefined" && val instanceof URLSearchParams;
  14. }
  15. function forEach(obj, fn) {
  16. if (obj === null || typeof obj === "undefined") {
  17. return;
  18. }
  19. if (typeof obj !== "object") {
  20. obj = [obj];
  21. }
  22. if (isArray(obj)) {
  23. for (let i = 0, l = obj.length; i < l; i++) {
  24. fn.call(null, obj[i], i, obj);
  25. }
  26. } else {
  27. for (const key in obj) {
  28. if (Object.prototype.hasOwnProperty.call(obj, key)) {
  29. fn.call(null, obj[key], key, obj);
  30. }
  31. }
  32. }
  33. }
  34. function isPlainObject(obj) {
  35. return Object.prototype.toString.call(obj) === "[object Object]";
  36. }
  37. function deepMerge() {
  38. const result = {};
  39. function assignValue(val, key) {
  40. if (typeof result[key] === "object" && typeof val === "object") {
  41. result[key] = deepMerge(result[key], val);
  42. } else if (typeof val === "object") {
  43. result[key] = deepMerge({}, val);
  44. } else {
  45. result[key] = val;
  46. }
  47. }
  48. for (let i = 0, l = arguments.length; i < l; i++) {
  49. forEach(arguments[i], assignValue);
  50. }
  51. return result;
  52. }
  53. function isUndefined(val) {
  54. return typeof val === "undefined";
  55. }
  56. exports.deepMerge = deepMerge;
  57. exports.forEach = forEach;
  58. exports.isArray = isArray;
  59. exports.isDate = isDate;
  60. exports.isObject = isObject;
  61. exports.isPlainObject = isPlainObject;
  62. exports.isURLSearchParams = isURLSearchParams;
  63. exports.isUndefined = isUndefined;