|
1 | | -// in progress |
| 1 | +/** |
| 2 | + * compares two objects or arrays |
| 3 | + * @param {Array or Object} a - The Array or Object to compare |
| 4 | + * @param {Array or Object} b - The Array or Object to compare |
| 5 | + * @return {boolean} |
| 6 | + */ |
| 7 | + |
| 8 | +// Helper returns a value's internal object [[Class]]; |
| 9 | +const getClass = (obj) => { |
| 10 | + return Object.prototype.toString.call(obj); |
| 11 | +}; |
| 12 | + |
| 13 | +const isEqual = (a, b) => { |
| 14 | + // Assumes that both params will be of the same data structure type. |
| 15 | + // If arrays: |
| 16 | + if (Array.isArray(a)) { |
| 17 | + for (let i = 0; i <= a.length; i++) { |
| 18 | + if (a[i] !== b[i]) { |
| 19 | + return false; |
| 20 | + } else { |
| 21 | + return true; |
| 22 | + } |
| 23 | + } |
| 24 | + // If objects: |
| 25 | + } else { |
| 26 | + // If a and b reference the same value, return true: |
| 27 | + if (a === b) return true; |
| 28 | + |
| 29 | + // If a and b are !both Objects, return false: |
| 30 | + if (typeof a != typeof b) return false; |
| 31 | + |
| 32 | + // If type is number: |
| 33 | + // TODO |
| 34 | + |
| 35 | + // Get internal [[class]]: |
| 36 | + const aClass = getClass(a); |
| 37 | + const bClass = getClass(b); |
| 38 | + // If classes are different, return false: |
| 39 | + if (aClass != bClass) return false; |
| 40 | + |
| 41 | + // If String, Number, or Boolean objects: |
| 42 | + if ( |
| 43 | + aClass == '[object Boolean]' || |
| 44 | + aClass == '[object String]' || |
| 45 | + aClass == '[object Error]' |
| 46 | + ) { |
| 47 | + if (a.toString() != b.toString()) return false; |
| 48 | + } |
| 49 | + |
| 50 | + // Grab the keys: |
| 51 | + const aKeys = Object.keys(a); |
| 52 | + const bKeys = Object.keys(b); |
| 53 | + |
| 54 | + // if !same # of keys, return false: |
| 55 | + if (aKeys.length !== bKeys.length) { |
| 56 | + return false; |
| 57 | + } |
| 58 | + |
| 59 | + // Check if they have the same keys: |
| 60 | + if ( |
| 61 | + !aKeys.every((key) => { |
| 62 | + return b.hasOwnProperty(key); |
| 63 | + }) |
| 64 | + ) { |
| 65 | + return false; |
| 66 | + } |
| 67 | + |
| 68 | + // Check key values - recursion: |
| 69 | + return aKeys.every((key) => { |
| 70 | + return isEqual(a[key], b[key]); |
| 71 | + }); |
| 72 | + } |
| 73 | + return false; |
| 74 | +}; |
| 75 | + |
| 76 | +module.exports = isEqual; |
0 commit comments