EasyJavaScriptTypeScript

Shallow Equal

ReactEqualityObjects

Implement solve(a, b) — a shallow equality check used internally by
React.memo and PureComponent.

Two values are shallowly equal when:

  • They are strictly equal (===), OR
  • Both are plain objects with the same keys and same (strictly equal) values.

Arrays are compared element-by-element at one level.

solve({ a: 1 }, { a: 1 })   // true
solve({ a: 1 }, { a: 2 })   // false
solve([1, 2],  [1, 2])      // true

Sample tests

Test #1Same primitives
Input: [1,1]
Output: true
Test #2Same shape objects
Input: [{"a":1,"b":2},{"a":1,"b":2}]
Output: true
Test #3Different value
Input: [{"a":1},{"a":2}]
Output: false
Test #4Different key count
Input: [{"a":1,"b":2},{"a":1}]
Output: false
Test #5null === null
Input: [null,null]
Output: true