Several refactorings
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 00425e1 · Browse files · 10 files·+109 added−105 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
10 files+109 added−105 removed
- tests:+2 added−1 removed
- other:+107 added−104 removed
Provenance
- Commit
c7f8f5b- Tree
583f53c- Author
Michel Weststrate <mweststrate@fb.com>- Committer
Michel Weststrate <mweststrate@fb.com>- Parent
00425e1
10 files changed+109 added−105 removed
modified:__tests__/tsconfig.json+2 added-1 removed
123455678{ "include": ["*", "../dist"], "compilerOptions": { "lib": ["es2015"], "strict": true "strict": true, "noUnusedLocals": false }}modified:src/common.ts+53 added-45 removed
1 import {2 Objectish,3- ObjectishNoSet,3 Drafted,4 AnyObject,5 AnyArray,6 AnyMap,4 unmodified lines11 /** Use a class type for `nothing` so its type is unique */12 export class Nothing {13 // This lets us do `Exclude<T, Nothing>`14 // TODO: do this better, use unique symbol instead15+ // @ts-ignore16 private _: any17 }18 19 const hasSymbol = typeof Symbol !== "undefined"36 unmodified lines56 export function isDraftable(value: any): boolean {57 if (!value) return false58 return (59 isPlainObject(value) ||60+ Array.isArray(value) ||61 !!value[DRAFTABLE] ||62 !!value.constructor[DRAFTABLE] ||63 isMap(value) ||64 isSet(value)1 unmodified line66 }67 68 export function isPlainObject(value: any): boolean {69 if (!value || typeof value !== "object") return false69- if (Array.isArray(value)) return true70 const proto = Object.getPrototypeOf(value)71 return !proto || proto === Object.prototype72 }73 19 unmodified lines93 obj: T,94 iter: (key: string | number, value: any, source: T) => void95 ): void96 export function each(obj: any, iter: any) {97- if (Array.isArray(obj) || isMap(obj) || isSet(obj)) {98- obj.forEach((entry: any, index: any) => iter(index, entry, obj))99- } else if (obj && typeof obj === "object") {97+ if (getArchtype(obj) === Archtype.Object) {98 ownKeys(obj).forEach(key => iter(key, obj[key], obj))99 } else {102- die()100+ obj.forEach((entry: any, index: any) => iter(index, entry, obj))101 }102 }103 104 export function isEnumerable(base: AnyObject, prop: PropertyKey): boolean {105 const desc = Object.getOwnPropertyDescriptor(base, prop)106 return desc && desc.enumerable ? true : false107 }108 111-// TODO: use draft meta data if present?112-// make refelction methods to determine types?113-export function has(thing: any, prop: PropertyKey): boolean {114- return !thing115- ? false109+export enum Archtype {110+ Object,111+ Array,112+ Map,113+ Set114+}115+116+const toArchType = {117+ proxy_object: Archtype.Object,118+ es5_object: Archtype.Object,119+ proxy_array: Archtype.Array,120+ es5_array: Archtype.Array,121+ map: Archtype.Map,122+ set: Archtype.Set123+}124+125+export function getArchtype(thing: any): Archtype {126+ if (!thing) die()127+ if (thing[DRAFT_STATE]) {128+ // @ts-ignore129+ return toArchType[(thing as Drafted)[DRAFT_STATE].type]130+ }131+ return Array.isArray(thing)132+ ? Archtype.Array133 : isMap(thing)134+ ? Archtype.Map135+ : isSet(thing)136+ ? Archtype.Set137+ : Archtype.Object138+}139+140+export function has(thing: any, prop: PropertyKey): boolean {141+ return getArchtype(thing) === Archtype.Map142 ? thing.has(prop)143 : Object.prototype.hasOwnProperty.call(thing, prop)144 }145 121-// TODO: use draft meta data if present?146 export function get(thing: AnyMap | AnyObject, prop: PropertyKey): any {123- return isMap(thing) ? thing.get(prop) : thing[prop as any]147+ // @ts-ignore148+ return getArchtype(thing) === Archtype.Map ? thing.get(prop) : thing[prop]149 }150 126-// TODO: measure fast vs slow path, use type switch instead127-export function set(parent: Drafted, prop: PropertyKey, value: any) {128- // fast path switch on meta data129- if (parent[DRAFT_STATE])130- switch (parent[DRAFT_STATE].type) {131- case "map":132- parent.set(prop, value)133- break134- case "set":135- parent.delete(prop)136- parent.add(value)137- break138- default:139- parent[prop] = value140- }141-142- // slow path143- parent[prop] = value144- if (isMap(parent)) {145- parent.set(prop, value)146- } else if (isSet(parent)) {147- // In this case, the `prop` is actually a draft.148- parent.delete(prop)149- parent.add(value)150- } else {151- parent[prop] = value151+export function set(thing: any, propOrOldValue: PropertyKey, value: any) {152+ switch (getArchtype(thing)) {153+ case Archtype.Map:154+ thing.set(propOrOldValue, value)155+ break156+ case Archtype.Set:157+ thing.delete(propOrOldValue)158+ thing.add(value)159+ break160+ default:161+ thing[propOrOldValue] = value162 }163 }164 165 export function is(x: any, y: any): boolean {48 unmodified lines214 })215 return clone216 }217 208-export function freeze<T extends Objectish>(209- obj: T,210- deep: boolean = false211-): void {218+export function freeze(obj: any, deep: boolean = false): void {219 if (!isDraftable(obj) || isDraft(obj) || Object.isFrozen(obj)) return213- if (isSet(obj)) {220+ const type = getArchtype(obj)221+ if (type === Archtype.Set) {222 obj.add = obj.clear = obj.delete = dontMutateFrozenCollections as any215- } else if (isMap(obj)) {223+ } else if (type === Archtype.Map) {224 obj.set = obj.clear = obj.delete = dontMutateFrozenCollections as any225 }226 Object.freeze(obj)227 if (deep) each(obj, (_, value) => freeze(value, true))21 unmodified linesmodified:src/es5.ts-3 removed
4 unmodified lines5 is,6 isDraft,7 isDraftable,8 isEnumerable,9- isMap,10- isSet,9 shallowCopy,10 DRAFT_STATE,11 latest,12 createHiddenProperty3 unmodified lines16 import {17 ImmerState,18 Drafted,19 AnyObject,22- AnyMap,20 Objectish,21 ImmerBaseState,22 AnyArray23 } from "./types"283 unmodified linesmodified:src/finalize.ts-2 removed
5 unmodified lines6 has,7 is,8 get,9 each,10- isMap,11- isEnumerable,10 DRAFT_STATE,11 NOTHING,12 freeze,13 shallowCopy,202 unmodified linesmodified:src/immer.ts+9 added-15 removed
7 unmodified lines8 isSet,9 isMap,10 isDraftable,11 DRAFT_STATE,12- NOTHING,13- isPlainObject,14- DRAFTABLE,15- die12+ NOTHING13 } from "./common"14 import {ImmerScope} from "./scope"15 import {16 ImmerState,141 unmodified lines158 }159 160 produceWithPatches(arg1: any, arg2?: any, arg3?: any): any {161 if (typeof arg1 === "function") {165- const self = this162 return (state: any, ...args: any[]) =>163 this.produceWithPatches(state, (draft: any) => arg1(draft, ...args))164 }165 // non-curried form78 unmodified lines244 createProxy<T extends Objectish>(245 value: T,246 parent?: ImmerState247 ): Drafted<T, ImmerState> {252- let draft: Drafted253- // TODO: use switch + type discovery>254- if (isMap(value)) draft = proxyMap(value, parent)255- else if (isSet(value)) draft = proxySet(value, parent)256- else {257- // createProxy should be guarded by isDraftable, so we know we can safely draft258- draft = this.useProxies259- ? createProxy(value, parent)260- : createES5Proxy(value, parent)261- }248+ // precondition: createProxy should be guarded by isDraftable, so we know we can safely draft249+ const draft: Drafted = isMap(value)250+ ? proxyMap(value, parent)251+ : isSet(value)252+ ? proxySet(value, parent)253+ : this.useProxies254+ ? createProxy(value, parent)255+ : createES5Proxy(value, parent)256 257 const scope = parent ? parent.scope : ImmerScope.current!258 scope.drafts.push(draft)259 return draft14 unmodified linesmodified:src/patches.ts+33 added-32 removed
1-import {get, each, isMap, isSet, has, die} from "./common"1+import {get, each, isMap, has, die, getArchtype, Archtype} from "./common"2 import {Patch, ImmerState} from "./types"3 import {SetState} from "./set"4 import {ES5ArrayState, ES5ObjectState} from "./es5"5 import {ProxyArrayState, ProxyObjectState} from "./proxy"163 unmodified lines169 const {path, op} = patch170 171 if (!path.length) die()172 173- let base = draft173+ let base: any = draft174 for (let i = 0; i < path.length - 1; i++) {175 base = get(base, path[i])176 if (!base || typeof base !== "object")177 throw new Error("Cannot apply patch, path doesn't resolve: " + path.join("/")) // prettier-ignore178 }179 180+ const type = getArchtype(base)181 const value = deepClonePatchValue(patch.value) // used to clone patch to ensure original patch is not modified, see #411181-182 const key = path[path.length - 1]183 switch (op) {184 case "replace":185+ switch (type) {185- if (isMap(base)) {186- base.set(key, value)187- } else if (isSet(base)) {188- throw new Error('Sets cannot have "replace" patches.')189- } else {190- // if value is an object, then it's assigned by reference191- // in the following add or remove ops, the value field inside the patch will also be modifyed192- // so we use value from the cloned patch193- // @ts-ignore194- base[key] = value186+ case Archtype.Map:187+ return base.set(key, value)188+ case Archtype.Set:189+ throw new Error('Sets cannot have "replace" patches.')190+ default:191+ // if value is an object, then it's assigned by reference192+ // in the following add or remove ops, the value field inside the patch will also be modifyed193+ // so we use value from the cloned patch194+ // @ts-ignore195+ return (base[key] = value)196 }197 break198 case "add":198- if (isSet(base)) {199- base.delete(patch.value)199+ switch (type) {200+ case Archtype.Array:201+ return base.splice(key as any, 0, value)202+ case Archtype.Map:203+ return base.set(key, value)204+ case Archtype.Set:205+ return base.add(value)206+ default:207+ return (base[key] = value)208 }201-202- Array.isArray(base)203- ? base.splice(key as any, 0, value)204- : isMap(base)205- ? base.set(key, value)206- : isSet(base)207- ? base.add(value)208- : ((base as any)[key] = value)209- break209 case "remove":211- Array.isArray(base)212- ? base.splice(key as any, 1)213- : isMap(base)214- ? base.delete(key)215- : isSet(base)216- ? base.delete(patch.value)217- : delete (base as any)[key]218- break210+ switch (type) {211+ case Archtype.Array:212+ return base.splice(key as any, 1)213+ case Archtype.Map:214+ return base.delete(key)215+ case Archtype.Set:216+ return base.delete(patch.value)217+ default:218+ return delete base[key]219+ }220 default:221 throw new Error("Unsupported patch operation: " + op)222 }223 })20 unmodified linesmodified:src/proxy.ts+2 added-4 removed
2 unmodified lines3 each,4 has,5 is,6 isDraftable,7- isMap,8- isSet,7 shallowCopy,8 DRAFT_STATE,9 latest10 } from "./common"76 unmodified lines87 // So the trick is to use 'state' as the actual 'target'! (and make sure we intercept everything)88 // Note that in the case of an array, we put the state in an array to have better Reflect defaults ootb89 let target: T = state as any90 let traps: ProxyHandler<object | Array<any>> = objectTraps93- if (Array.isArray(base)) {91+ if (isArray) {92 target = [state] as any93 traps = arrayTraps94 }95 76 unmodified lines172 const owner = latest(state)173 const desc = Reflect.getOwnPropertyDescriptor(owner, prop)174 if (desc) {175 desc.writable = true178- desc.configurable = !Array.isArray(owner) || prop !== "length"176+ desc.configurable = state.type !== "proxy_array" || prop !== "length"177 }178 return desc179 },180 defineProperty() {72 unmodified linesmodified:src/set.ts-1 removed
109 unmodified linesExpand all11011111211311411411511611724 unmodified lines109 unmodified linesExpand all return this.values() }
forEach(cb: (value: V, key: V, self: this) => void, thisArg?: any) { const state = this[DRAFT_STATE] const iterator = this.values() let result = iterator.next() while (!result.done) { cb.call(thisArg, result.value, result.value, this)24 unmodified linesmodified:package.json+8 added-1 removed
89 unmodified lines90 "transform": {91 "\\.js$": "babel-jest",92 "\\.ts$": "ts-jest"93 },94- "preset": "ts-jest/presets/js-with-babel"94+ "preset": "ts-jest/presets/js-with-babel",95+ "globals": {96+ "ts-jest": {97+ "tsConfig": {98+ "noUnusedLocals": false99+ }100+ }101+ }102 }103 }modified:tsconfig.json+2 added-1 removed
6 unmodified lines7 "strict": true,8 "declaration": true,9 "importHelpers": false,10 "noImplicitAny": true,11- "esModuleInterop": true11+ "esModuleInterop": true,12+ "noUnusedLocals": true13 }14 }