feat: add support of non-primitive keys for `Maps`
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by keenondrums · committed by Alec Larson · parent 5093fd0 · Browse files · 6 files·+123 added−49 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
6 files+123 added−49 removed
- tests:+81 added−5 removed
- other:+42 added−44 removed
Provenance
- Commit
6501ec5- Tree
3287256- Author
keenondrums <andrey.goncharov+it@protonmail.com>- Committer
Alec Larson <alec.stanford.larson@gmail.com>- Parent
5093fd0
6 files changed+123 added−49 removed
modified:__tests__/base.js+40 added-3 removed
307 unmodified lines308 })309 expect(nextState).toBe(baseState)310 })311 312+ it("supports key access for non-primitive keys", () => {313+ const key = {prop: "val"}314+ const base = new Map([[key, {id: 1, a: 1}]])315+ const value = base.get(key)316+ const nextState = produce(base, s => {317+ expect(s.get(key)).toEqual(value)318+ })319+ expect(nextState).toBe(base)320+ })321+322 it("supports iteration", () => {323 const base = new Map([324 ["first", {id: 1, a: 1}],325 ["second", {id: 2, a: 1}]75 unmodified lines401 })402 })403 404 it("supports forEach", () => {405+ const key1 = {prop: "val1"}406+ const key2 = {prop: "val2"}407 const base = new Map([408 ["first", {id: 1, a: 1}],397- ["second", {id: 2, a: 1}]409+ ["second", {id: 2, a: 1}],410+ [key1, {id: 3, a: 1}],411+ [key2, {id: 4, a: 1}]412 ])413 const result = produce(base, draft => {414 let sum1 = 0415 draft.forEach(({a}) => {416 sum1 += a417 })404- expect(sum1).toBe(2)418+ expect(sum1).toBe(4)419 let sum2 = 0420 draft.get("first").a = 10421 draft.get("second").a = 20422+ draft.get(key1).a = 30423+ draft.get(key2).a = 40424 draft.forEach(({a}) => {425 sum2 += a426 })411- expect(sum2).toBe(30)427+ expect(sum2).toBe(100)428 })429+ expect(result).not.toBe(base)430+ expect(base.get("first").a).toEqual(1)431+ expect(base.get("second").a).toEqual(1)432+ expect(base.get(key1).a).toEqual(1)433+ expect(base.get(key2).a).toEqual(1)434+ expect(result.get("first").a).toEqual(10)435+ expect(result.get("second").a).toEqual(20)436+ expect(result.get(key1).a).toEqual(30)437+ expect(result.get(key2).a).toEqual(40)438 })439 440 it("supports forEach mutation", () => {441 const base = new Map([20 unmodified lines462 expect(nextState.aMap).not.toBe(baseState.aMap)463 expect(nextState.aMap.get("force")).toEqual(true)464 })465 466+ it("can assign by a non-primitive key", () => {467+ const key = {prop: "val"}468+ const value = {id: 1, a: 1}469+ const base = new Map([[key, value]])470+ const nextState = produce(base, s => {471+ s.set(key, true)472+ })473+ expect(nextState).not.toBe(base)474+ expect(base.get(key)).toEqual(value)475+ expect(nextState.get(key)).toEqual(true)476+ })477+478 it("state stays the same if the the same item is assigned by key", () => {479 const nextState = produce(baseState, s => {480 s.aMap.set("jediTotal", 42)481 })1250 unmodified linesmodified:__tests__/patch.js+41 added-2 removed
156 unmodified lines157 true158 )159 })160 161+describe("simple assignment - 7", () => {162+ const key1 = {prop: "val1"}163+ const key2 = {prop: "val2"}164+ runPatchTest(165+ {x: new Map([[key1, 4]])},166+ d => {167+ d.x.set(key1, 5)168+ d.x.set(key2, 6)169+ },170+ [171+ {op: "replace", path: ["x", key1], value: 5},172+ {op: "add", path: ["x", key2], value: 6}173+ ],174+ [175+ {op: "replace", path: ["x", key1], value: 4},176+ {op: "remove", path: ["x", key2]}177+ ],178+ true179+ )180+})181+182 describe("delete 1", () => {183 runPatchTest(184 {x: {y: 4}},185 d => {26 unmodified lines212 true213 )214 })215 195-describe("delete 4", () => {216+describe("delete 5", () => {217+ const key1 = {prop: "val1"}218+ const key2 = {prop: "val2"}219 runPatchTest(220+ {x: new Map([[key1, 1], [key2, 2]])},221+ d => {222+ d.x.delete(key1)223+ d.x.delete(key2)224+ },225+ [{op: "remove", path: ["x", key1]}, {op: "remove", path: ["x", key2]}],226+ [227+ {op: "add", path: ["x", key1], value: 1},228+ {op: "add", path: ["x", key2], value: 2}229+ ],230+ true231+ )232+})233+234+describe("delete 6", () => {235+ runPatchTest(236 new Set(["x", 1]),237 d => {238 d.delete("x")239 },2 unmodified lines242 true243 )244 })245 207-describe("delete 5", () => {246+describe("delete 7", () => {247 runPatchTest(248 {x: new Set(["y", 1])},249 d => {250 d.x.delete("y")482 unmodified linesmodified:src/common.js+23 added-17 removed
31 unmodified lines32333435363738394041423637383940414344424643444546475051525354555648495051525354555662 unmodified lines11912012112212312412512612712812913013113213313413513613713813912 unmodified lines31 unmodified lines}
// We use Maps as `drafts` for Sets, not Objects// See proxy.jsexport function assignSet(target, ...mapOverrides) { mapOverrides.forEach(override => { for (const value of override.values()) { // When we add new drafts we have to remove their originals if present const originalValue = original(value) if (originalValue) { target.delete(originalValue)export function assignSet(target, override) { for (const value of override.values()) { // When we add new drafts we have to remove their originals if present const originalValue = original(value) if (originalValue) { target.delete(originalValue) } target.add(value) } }) target.add(value) } return target}
export function assignMap(target, ...objOverrides) { objOverrides.forEach(override => { for (let key in override) { if (has(override, key)) { target.set(key, override[key]) } }// We use Maps as `drafts` for Maps, not Objects// See proxy.jsexport function assignMap(target, override) { override.forEach((value, key) => { target.set(key, value) }) return target}
62 unmodified lines return !!desc && desc.enumerable}
export function has(thing, prop) { if (isMap(thing)) { return thing.has(prop) } return Object.prototype.hasOwnProperty.call(thing, prop)}
export function get(thing, prop) { if (isMap(thing)) { return thing.get(prop) } return thing[prop]}
export function is(x, y) { // From: https://github.com/facebook/fbjs/blob/c69904a511b900266935168223063dd8772dfc40/packages/fbjs/src/core/shallowEqual.js if (x === y) { return x !== 0 || 1 / x === 1 / y12 unmodified linesmodified:src/immer.js+1 added-1 removed
251 unmodified lines252 const path =253 isDraftProp &&254 needPatches &&255 !isSet(parent) &&256- !state.assigned[prop]256+ !has(state.assigned, prop)257 ? rootPath.concat(prop)258 : null259 260 // Drafts owned by `scope` are finalized here.50 unmodified linesmodified:src/patches.js+7 added-19 removed
1-import {each, isMap, isSet} from "./common"1+import {get, each, isMap, isSet, has} from "./common"2 3 export function generatePatches(state, basePath, patches, inversePatches) {4 const generatePatchesFn = Array.isArray(state.base)5 ? generateArrayPatches6- : isMap(state.base)7- ? generatePatchesFromAssigned(8- (map, key) => map.get(key),9- (map, key) => map.has(key)10- )6 : isSet(state.base)7 ? generateSetPatches13- : generatePatchesFromAssigned(14- (obj, key) => obj[key],15- (obj, key) => key in obj16- )8+ : generatePatchesFromAssigned()9 10 generatePatchesFn(state, basePath, patches, inversePatches)11 }12 65 unmodified lines78 })79 }80 }81 90-function generatePatchesFromAssigned(getValueByKey, hasKey) {82+function generatePatchesFromAssigned() {83 return function(state, basePath, patches, inversePatches) {84 const {base, copy} = state85 each(state.assigned, (key, assignedValue) => {94- const origValue = getValueByKey(base, key)95- const value = getValueByKey(copy, key)86+ const origValue = get(base, key)87+ const value = get(copy, key)88 const op = !assignedValue89 ? "remove"98- : hasKey(base, key)90+ : has(base, key)91 ? "replace"92 : "add"93 if (origValue === value && op === "replace") return94 const path = basePath.concat(key)56 unmodified lines151 draft = patch.value152 } else {153 let base = draft154 for (let i = 0; i < path.length - 1; i++) {163- if (isMap(base)) {164- base = base.get(path[i])155+ base = get(base, path[i])165- } else {166- base = base[path[i]]167- }156 if (!base || typeof base !== "object")157 throw new Error("Cannot apply patch, path doesn't resolve: " + path.join("/")) // prettier-ignore158 }159 const key = path[path.length - 1]45 unmodified linesmodified:src/proxy.js+11 added-7 removed
54 unmodified lines55 proxyTarget = [state]56 traps = arrayTraps57 } else if (isMap(base)) {58 traps = mapTraps59+ // Maps need to support non-primitive keys and objects do not support other objects as keys60+ state.drafts = new Map()61+ state.assigned = new Map()62 } else if (isSet(base)) {63 traps = setTraps64 // We use values of a Set as keys and objects do not support other objects as keys65 state.drafts = new Map()66+ // Sets do not need .assigned override since you cannot really assign (read as 'replace') any value in s Set. You can only add or remove values67 }68 69 const {revoke, proxy} = Proxy.revocable(proxyTarget, traps)70 137 unmodified lines208 set: state => (key, value) => {209 const stateSource = source(state)210 if (!stateSource.has(key) || stateSource.get(key) !== value) {211 markChanged(state)208- state.assigned[key] = true212+ state.assigned.set(key, true)213 state.copy.set(key, value)214 }215 return state.draft216 },217 delete: state => key => {218 markChanged(state)215- state.assigned[key] = false219+ state.assigned.set(key, false)220 return state.copy.delete(key)221 },222 clear: state => () => {223 markChanged(state)220- state.assigned = {}224+ state.assigned = new Map()225 for (const key of source(state).keys()) {222- state.assigned[key] = false226+ state.assigned.set(key, false)227 }228 return state.copy.clear()229 },230 forEach: (state, _, receiver) => (cb, thisArg) =>1 unmodified line232 const value = receiver.get(key)233 cb.call(thisArg, value, key, map)234 }),235 get: state => key => {232- if (!state.modified && has(state.drafts, key)) {233- return state.drafts[key]236+ if (!state.modified && state.drafts.has(key)) {237+ return state.drafts.get(key)238 }239 240 if (state.modified && state.copy.has(key)) {241 return state.copy.get(key)7 unmodified lines249 250 const draft = createProxy(value, state)251 252 if (!state.modified) {249- state.drafts[key] = draft253+ state.drafts.set(key, draft)254 } else {255 state.copy.set(key, draft)256 }257 174 unmodified lines