Skip to content

Commit

Permalink
Merge pull request #249 from aleclarson/patch1
Browse files Browse the repository at this point in the history
simplify es5 object key diffing
  • Loading branch information
mweststrate committed Nov 19, 2018
2 parents 4613b06 + 5792b83 commit 5360e6c
Showing 1 changed file with 18 additions and 28 deletions.
46 changes: 18 additions & 28 deletions src/es5.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import {
PROXY_STATE,
shallowCopy,
RETURNED_AND_MODIFIED_ERROR,
has,
each,
finalize
} from "./common"
Expand Down Expand Up @@ -168,9 +169,23 @@ function diffKeys(from, to) {
}

function hasObjectChanges(state) {
const baseKeys = Object.keys(state.base)
const keys = Object.keys(state.proxy)
return !shallowEqual(baseKeys, keys)
const {base, proxy} = state

// Search for added keys. Start at the back, because non-numeric keys
// are ordered by time of definition on the object.
const keys = Object.keys(proxy)
for (let i = keys.length; i !== 0; ) {
const key = keys[--i]

// The `undefined` check is a fast path for pre-existing keys.
if (base[key] === undefined && !has(base, key)) {
return true
}
}

// Since no keys have been added, we can compare lengths to know if an
// object has been deleted.
return keys.length !== Object.keys(base).length
}

function hasArrayChanges(state) {
Expand Down Expand Up @@ -236,31 +251,6 @@ export function produceEs5(baseState, producer, patchListener) {
}
}

function shallowEqual(objA, objB) {
//From: https://github.com/facebook/fbjs/blob/c69904a511b900266935168223063dd8772dfc40/packages/fbjs/src/core/shallowEqual.js
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
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
}

function createHiddenProperty(target, prop, value) {
Object.defineProperty(target, prop, {
value: value,
Expand Down

0 comments on commit 5360e6c

Please sign in to comment.