Skip to content
Myr

Add support for arrays

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by Michel Weststrate · committed by Michel Weststrate · parent 46e1d5d · Browse files · 3 files+56 added−9 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

3 files+56 added−9 removed

  • tests:+39 added−1 removed
  • other:+17 added−8 removed

3 files+56 added−9 removed

modified:__tests__/base.js+39 added-1 removed
modified:immer.js+16 added-7 removed
29 unmodified lines
30 set(target, prop, value) {31 const current = proxyThing(getCurrentSource(target)[prop])32 const newValue = proxyThing(value)33 if (current !== newValue) {34 const copy = getOrCreateObjectCopy(target)34 const copy = getOrCreateCopy(target)35 copy[prop] = newValue36 }37 return true38 },39 deleteProperty(target, property) {40 const copy = getOrCreateObjectCopy(target)40 const copy = getOrCreateCopy(target)41 delete copy[property]42 return true43 }44 }4546 function getOrCreateObjectCopy(object) {46 function getOrCreateCopy(object) {47 let copy = copies.get(object)48 if (!copy) {49 copy = Object.assign({}, object)49 copy = Array.isArray(object) ? object.slice() : Object.assign({}, object)50 copies.set(object, copy)51 }52 return copy53 }
3 unmodified lines
57 return copy || object58 }5960 function proxyThing(thing) {61 if (isPlainObject(thing)) return proxyObject(thing)62 // TODO: array61 if (isPlainObject(thing) || Array.isArray(thing)) return proxyObject(thing)62 return thing63 }6465 function proxyObject(object) {
5 unmodified lines
71 }7273 function finalizeThing(thing) {74 if (isPlainObject(thing)) return finalizeObject(thing)75 if (Array.isArray(thing)) return finalizeArray(thing)76 return thing77 }7879 function hasObjectChanges(thing) {
10 unmodified lines
90 }9192 function finalizeObject(thing) {93 if (!hasObjectChanges(thing)) return thing94 const copy = getOrCreateObjectCopy(thing)94 const copy = getOrCreateCopy(thing)95 Object.keys(copy).forEach(prop => {96 copy[prop] = finalizeThing(copy[prop])97 })98 return copy99 }100101 function finalizeArray(thing) {102 if (!hasObjectChanges(thing)) return thing103 const copy = getOrCreateCopy(thing)104 copy.forEach((value, index) => {105 copy[index] = finalizeThing(copy[index])106 })107 return copy108 }109110 const rootClone = proxyThing(baseState)111 thunk(rootClone)112 return finalizeThing(baseState)113}
8 unmodified lines
modified:package.json+1 added-1 removed