shallow-equal.js (1561B)
1 /* This Source Code Form is subject to the terms of the Mozilla Public 2 * License, v. 2.0. If a copy of the MPL was not distributed with this 3 * file, You can obtain one at <http://mozilla.org/MPL/2.0/>. */ 4 5 /** 6 * Shallow equal will consider equal: 7 * - exact same values (strict '===' equality) 8 * - distinct array instances having the exact same values in them (same number and strict equality). 9 * - distinct object instances having the exact same attributes and values. 10 * 11 * It will typically consider different array and object whose values 12 * aren't strictly equal. You may consider using "deep equality" checks for this scenario. 13 */ 14 export function shallowEqual(value, other) { 15 if (value === other) { 16 return true; 17 } 18 19 if (Array.isArray(value) && Array.isArray(other)) { 20 return arrayShallowEqual(value, other); 21 } 22 23 if (isObject(value) && isObject(other)) { 24 return objectShallowEqual(value, other); 25 } 26 27 return false; 28 } 29 30 export function arrayShallowEqual(value, other) { 31 // Redo this check in case we are called directly from the selectors. 32 if (value === other) { 33 return true; 34 } 35 return value.length === other.length && value.every((k, i) => k === other[i]); 36 } 37 38 function objectShallowEqual(value, other) { 39 const existingKeys = Object.keys(other); 40 const keys = Object.keys(value); 41 42 return ( 43 keys.length === existingKeys.length && 44 keys.every((k, i) => k === existingKeys[i]) && 45 keys.every(k => value[k] === other[k]) 46 ); 47 } 48 49 function isObject(value) { 50 return typeof value === "object" && !!value; 51 }