Skip to content
Myr

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

10 files+109 added−105 removed

modified:__tests__/tsconfig.json+2 added-1 removed
modified:src/common.ts+53 added-45 removed
1import {2 Objectish,3 ObjectishNoSet,3 Drafted,4 AnyObject,5 AnyArray,6 AnyMap,
4 unmodified lines
11/** Use a class type for `nothing` so its type is unique */12export class Nothing {13 // This lets us do `Exclude<T, Nothing>`14 // TODO: do this better, use unique symbol instead15 // @ts-ignore16 private _: any17}1819const hasSymbol = typeof Symbol !== "undefined"
36 unmodified lines
56export 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 line
66}6768export 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 lines
93 obj: T,94 iter: (key: string | number, value: any, source: T) => void95): void96export 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}103104export function isEnumerable(base: AnyObject, prop: PropertyKey): boolean {105 const desc = Object.getOwnPropertyDescriptor(base, prop)106 return desc && desc.enumerable ? true : false107}108111// TODO: use draft meta data if present?112// make refelction methods to determine types?113export function has(thing: any, prop: PropertyKey): boolean {114 return !thing115 ? false109export enum Archtype {110 Object,111 Array,112 Map,113 Set114}115116const 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}124125export 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}139140export function has(thing: any, prop: PropertyKey): boolean {141 return getArchtype(thing) === Archtype.Map142 ? thing.has(prop)143 : Object.prototype.hasOwnProperty.call(thing, prop)144}145121// TODO: use draft meta data if present?146export 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}150126// TODO: measure fast vs slow path, use type switch instead127export 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 }141142 // 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] = value151export 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}164165export function is(x: any, y: any): boolean {
48 unmodified lines
214 })215 return clone216}217208export function freeze<T extends Objectish>(209 obj: T,210 deep: boolean = false211): void {218export 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 lines
modified:src/es5.ts-3 removed
4 unmodified lines
5 is,6 isDraft,7 isDraftable,8 isEnumerable,9 isMap,10 isSet,9 shallowCopy,10 DRAFT_STATE,11 latest,12 createHiddenProperty
3 unmodified lines
16import {17 ImmerState,18 Drafted,19 AnyObject,22 AnyMap,20 Objectish,21 ImmerBaseState,22 AnyArray23} from "./types"
283 unmodified lines
modified:src/finalize.ts-2 removed
5 unmodified lines
6 has,7 is,8 get,9 each,10 isMap,11 isEnumerable,10 DRAFT_STATE,11 NOTHING,12 freeze,13 shallowCopy,
202 unmodified lines
modified:src/immer.ts+9 added-15 removed
7 unmodified lines
8 isSet,9 isMap,10 isDraftable,11 DRAFT_STATE,12 NOTHING,13 isPlainObject,14 DRAFTABLE,15 die12 NOTHING13} from "./common"14import {ImmerScope} from "./scope"15import {16 ImmerState,
141 unmodified lines
158 }159160 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 form
78 unmodified lines
244 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)256257 const scope = parent ? parent.scope : ImmerScope.current!258 scope.drafts.push(draft)259 return draft
14 unmodified lines
modified:src/patches.ts+33 added-32 removed
1import {get, each, isMap, isSet, has, die} from "./common"1import {get, each, isMap, has, die, getArchtype, Archtype} from "./common"2import {Patch, ImmerState} from "./types"3import {SetState} from "./set"4import {ES5ArrayState, ES5ObjectState} from "./es5"5import {ProxyArrayState, ProxyObjectState} from "./proxy"
163 unmodified lines
169 const {path, op} = patch170171 if (!path.length) die()172173 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 }179180 const type = getArchtype(base)181 const value = deepClonePatchValue(patch.value) // used to clone patch to ensure original patch is not modified, see #411181182 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 }201202 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 lines
modified:src/proxy.ts+2 added-4 removed
2 unmodified lines
3 each,4 has,5 is,6 isDraftable,7 isMap,8 isSet,7 shallowCopy,8 DRAFT_STATE,9 latest10} from "./common"
76 unmodified lines
87 // 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 lines
172 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 lines
modified:src/set.ts-1 removed
modified:package.json+8 added-1 removed
89 unmodified lines
90 "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 lines
7 "strict": true,8 "declaration": true,9 "importHelpers": false,10 "noImplicitAny": true,11 "esModuleInterop": true11 "esModuleInterop": true,12 "noUnusedLocals": true13 }14}