SHARE
TWEET

Untitled

a guest Mar 18th, 2019 49 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function equal(a, b) {
  2.   const typeA = Object.prototype.toString.call(a);
  3.   const typeB = Object.prototype.toString.call(b);
  4.   if (typeA === typeB) {
  5.     if (typeA === '[object Object]') {
  6.       // Object
  7.       let resultNum = 0;
  8.       let keyA = Object.keys(a);
  9.       let keyB = Object.keys(b);
  10.       if (keyA.length !== keyB.length) return false;
  11.       for (let i = 0;i < keyA.length;i++) {
  12.         let targetKey = keyA[i];
  13.         if (equal(b[targetKey], a[targetKey])) {
  14.           resultNum++;
  15.         } else {
  16.           return false;
  17.         }
  18.       }
  19.       return resultNum === keyA.length;
  20.     } else if (typeA === '[object Array]') {
  21.       // Array
  22.       if (a.length !== b.length) return false;
  23.       for (let i = -1, item = a[i];item=a[++i];){
  24.         if (!equal(item, b[i])) {
  25.           return false;
  26.         }
  27.       }
  28.       return true;
  29.     } else {
  30.       // Not Support
  31.       return a === b;
  32.     }
  33.   } else {
  34.     return false;
  35.   }
  36. }
  37.  
  38. let obj1 = { a: [1, '2'], b: 2};
  39. let obj2 = { b: 2, a: [1, '2']};
  40. let arr1 = [1, 2, { a: 1, b: 2 }, 9];
  41. let arr2 = [1, 2, { b: 2, a: 1 }, 9];
  42.  
  43. console.log("equal(obj1, obj2)", equal(obj1, obj2));
  44. console.log("equal(arr1, arr2)", equal(arr1, arr2));
  45. console.log("equal(obj1, arr1)", equal(obj1, arr1));
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top