Skip to content

Instantly share code, notes, and snippets.

@gaspaonrocks
Created July 26, 2018 14:14
Show Gist options
  • Select an option

  • Save gaspaonrocks/07854e7a6a60a58cd6ee16fc1d752f58 to your computer and use it in GitHub Desktop.

Select an option

Save gaspaonrocks/07854e7a6a60a58cd6ee16fc1d752f58 to your computer and use it in GitHub Desktop.

Revisions

  1. @gaspaonrocksBis gaspaonrocksBis created this gist Jul 26, 2018.
    58 changes: 58 additions & 0 deletions shallowEqual.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,58 @@
    const { hasOwnProperty } = Object.prototype.hasOwnProperty;

    /**
    * inlined Object.is polyfill to avoid requiring consumers ship their own
    * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is
    */
    function is(x, y) {
    // SameValue algorithm
    if (x === y) {
    // Steps 1-5, 7-10
    // Steps 6.b-6.e: +0 != -0
    // Added the nonzero y check to make Flow happy, but it is redundant
    return x !== 0 || y !== 0 || 1 / x === 1 / y;
    }
    // Step 6.a: NaN == NaN
    return x !== x && y !== y;
    }

    /**
    * Performs equality by iterating through keys on an object and returning false
    * when any key has values which are not strictly equal between the arguments.
    * Returns true when the values of all keys are strictly equal.
    */
    function shallowEqual(objA, objB) {
    if (is(objA, objB)) {
    return true;
    }

    if (
    typeof objA !== 'object' ||
    objA === null ||
    typeof objB !== 'object' ||
    objB === null
    ) {
    return false;
    }

    const keysA = Object.keys(objA);
    const keysB = Object.keys(objB);

    if (keysA.length !== keysB.length) {
    return false;
    }

    // Test for A's keys different from B.
    for (let i = 0; i < keysA.length; i++) {
    if (
    !hasOwnProperty.call(objB, keysA[i]) ||
    !is(objA[keysA[i]], objB[keysA[i]])
    ) {
    return false;
    }
    }

    return true;
    }

    export default shallowEqual;