Skip to content
Myr

common.ts

This file

Path

src/common.ts

240 lines · 6.3 KiB · TypeScript

Last changed by

Processed bunch of todosMichel Weststratebefore adoption00425e1

History of this file

Take it

Further cleanup in progressMichel Weststratebefore adoptionaeba1ff

lines 1–10why, one step back
1import {
2 Objectish,3 ObjectishNoSet,4 Drafted,5 AnyObject,6 AnyArray,7 AnyMap,8 AnySet,9 ImmerState10} from "./types"

Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0

lines 11–18why, one step back
11
12/** Use a class type for `nothing` so its type is unique */13export class Nothing {14 // This lets us do `Exclude<T, Nothing>`15 // TODO: do this better, use unique symbol instead16 private _: any17}18

Processed bunch of todosMichel Weststratebefore adoption00425e1

lines 19–22why, one step back
19const hasSymbol = typeof Symbol !== "undefined"
20export const hasMap = typeof Map !== "undefined"21export const hasSet = typeof Set !== "undefined"22

Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0

lines 23–25why, one step back
23/**
24 * The sentinel value returned by producers to replace the draft with undefined.25 */

Processed bunch of todosMichel Weststratebefore adoption00425e1

lines 26–28why, one step back
26export const NOTHING: Nothing = hasSymbol
27 ? Symbol("immer-nothing")28 : ({["immer-nothing"]: true} as any)

Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0

lines 29–37why, one step back
29
30/**31 * To let Immer treat your class instances as plain immutable objects32 * (albeit with a custom prototype), you must define either an instance property33 * or a static property on each of your custom classes.34 *35 * Otherwise, your class instance will never be drafted, which means it won't be36 * safe to mutate in a produce callback.37 */

Processed bunch of todosMichel Weststratebefore adoption00425e1

lines 38–40why, one step back
38export const DRAFTABLE: unique symbol = hasSymbol
39 ? Symbol("immer-draftable")40 : ("__$immer_draftable" as any)

Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0

line 41why, one step back
41

Processed bunch of todosMichel Weststratebefore adoption00425e1

lines 42–44why, one step back
42export const DRAFT_STATE: unique symbol = hasSymbol
43 ? Symbol("immer-state")44 : ("__$immer_state" as any)

Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0

line 45why, one step back
45

Processed bunch of todosMichel Weststratebefore adoption00425e1

lines 46–49why, one step back
46export const iteratorSymbol: typeof Symbol.iterator = hasSymbol
47 ? Symbol.iterator48 : ("@@iterator" as any)49

Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0

lines 50–66why, one step back
50/** Returns true if the given value is an Immer draft */
51export function isDraft(value: any): boolean {52 return !!value && !!value[DRAFT_STATE]53}5455/** Returns true if the given value can be drafted by Immer */56export function isDraftable(value: any): boolean {57 if (!value) return false58 return (59 isPlainObject(value) ||60 !!value[DRAFTABLE] ||61 !!value.constructor[DRAFTABLE] ||62 isMap(value) ||63 isSet(value)64 )65}66

TS type improvementsMichel Weststratebefore adoptiondd1808e

line 67why, one step back
67export function isPlainObject(value: any): boolean {

Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0

lines 68–74why, one step back
68 if (!value || typeof value !== "object") return false
69 if (Array.isArray(value)) return true70 const proto = Object.getPrototypeOf(value)71 return !proto || proto === Object.prototype72}7374/** Get the underlying object that is represented by the given draft */

Dropped Object.assignMichel Weststratebefore adoption79a1d2c

line 75why, one step back
75export function original<T>(value: Drafted<T>): T | undefined {

Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0

line 76why, one step back
76 if (value && value[DRAFT_STATE]) {

Dropped Object.assignMichel Weststratebefore adoption79a1d2c

line 77why, one step back
77 return value[DRAFT_STATE].base as any

Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0

lines 78–81why, one step back
78 }
79 // otherwise return undefined80}81

TS type improvementsMichel Weststratebefore adoptiondd1808e

line 82why, one step back
82export const ownKeys: (target: AnyObject) => PropertyKey[] =

Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0

lines 83–86why, one step back
83 typeof Reflect !== "undefined" && Reflect.ownKeys
84 ? Reflect.ownKeys85 : typeof Object.getOwnPropertySymbols !== "undefined"86 ? obj =>

🎵...killing me softly, with your fingers... 🎶Michel Weststratebefore adoption19a6b66

lines 87–89why, one step back
87 Object.getOwnPropertyNames(obj).concat(
88 Object.getOwnPropertySymbols(obj) as any89 )

Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0

lines 90–93why, one step back
90 : Object.getOwnPropertyNames
9192export function each<T extends Objectish>(93 obj: T,

Further cleanup in progressMichel Weststratebefore adoptionaeba1ff

line 94why, one step back
94 iter: (key: string | number, value: any, source: T) => void

TS type improvementsMichel Weststratebefore adoptiondd1808e

lines 95–96why, one step back
95): void
96export function each(obj: any, iter: any) {

Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0

line 97why, one step back
97 if (Array.isArray(obj) || isMap(obj) || isSet(obj)) {

TS type improvementsMichel Weststratebefore adoptiondd1808e

line 98why, one step back
98 obj.forEach((entry: any, index: any) => iter(index, entry, obj))

basic map tests succeedingMichel Weststratebefore adoption735c402

line 99why, one step back
99 } else if (obj && typeof obj === "object") {

Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0

line 100why, one step back
100 ownKeys(obj).forEach(key => iter(key, obj[key], obj))

basic map tests succeedingMichel Weststratebefore adoption735c402

line 101why, one step back
101 } else {

TS type improvementsMichel Weststratebefore adoptiondd1808e

line 102why, one step back
102 die()

Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0

lines 103–105why, one step back
103 }
104}105

Dropped Object.assignMichel Weststratebefore adoption79a1d2c

line 106why, one step back
106export function isEnumerable(base: AnyObject, prop: PropertyKey): boolean {

Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0

lines 107–110why, one step back
107 const desc = Object.getOwnPropertyDescriptor(base, prop)
108 return desc && desc.enumerable ? true : false109}110

TS type improvementsMichel Weststratebefore adoptiondd1808e

lines 111–112why, one step back
111// TODO: use draft meta data if present?
112// make refelction methods to determine types?

Processed bunch of todosMichel Weststratebefore adoption00425e1

line 113why, one step back
113export function has(thing: any, prop: PropertyKey): boolean {

basic map tests succeedingMichel Weststratebefore adoption735c402

lines 114–116why, one step back
114 return !thing
115 ? false116 : isMap(thing)

Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0

lines 117–120why, one step back
117 ? thing.has(prop)
118 : Object.prototype.hasOwnProperty.call(thing, prop)119}120

TS type improvementsMichel Weststratebefore adoptiondd1808e

lines 121–123why, one step back
121// TODO: use draft meta data if present?
122export function get(thing: AnyMap | AnyObject, prop: PropertyKey): any {123 return isMap(thing) ? thing.get(prop) : thing[prop as any]

Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0

lines 124–125why, one step back
124}
125

TS type improvementsMichel Weststratebefore adoptiondd1808e

lines 126–154why, one step back
126// TODO: measure fast vs slow path, use type switch instead
127export 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] = value152 }153}154

Further cleanup in progressMichel Weststratebefore adoptionaeba1ff

line 155why, one step back
155export function is(x: any, y: any): boolean {

Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0

lines 156–163why, one step back
156 // From: https://github.com/facebook/fbjs/blob/c69904a511b900266935168223063dd8772dfc40/packages/fbjs/src/core/shallowEqual.js
157 if (x === y) {158 return x !== 0 || 1 / x === 1 / y159 } else {160 return x !== x && y !== y161 }162}163

Further cleanup in progressMichel Weststratebefore adoptionaeba1ff

line 164why, one step back
164export function isMap(target: any): target is AnyMap {

Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0

lines 165–167why, one step back
165 return hasMap && target instanceof Map
166}167

Further cleanup in progressMichel Weststratebefore adoptionaeba1ff

line 168why, one step back
168export function isSet(target: any): target is AnySet {

Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0

lines 169–171why, one step back
169 return hasSet && target instanceof Set
170}171

Further cleanup in progressMichel Weststratebefore adoptionaeba1ff

line 172why, one step back
172export function latest(state: ImmerState): any {

Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0

lines 173–174why, one step back
173 return state.copy || state.base
174}

fixed most testsMichel Weststratebefore adoption385c0a4

line 175why, one step back
175

Further cleanup in progressMichel Weststratebefore adoptionaeba1ff

line 176why, one step back
176export function shallowCopy<T extends AnyObject | AnyArray>(

Some initial cleanupMichel Weststratebefore adoptionc53a75f

lines 177–179why, one step back
177 base: T,
178 invokeGetters?: boolean179): T

TS type improvementsMichel Weststratebefore adoptiondd1808e

line 180why, one step back
180export function shallowCopy(base: any, invokeGetters = false) {

Some initial cleanupMichel Weststratebefore adoptionc53a75f

lines 181–205why, one step back
181 if (Array.isArray(base)) return base.slice()
182 const clone = Object.create(Object.getPrototypeOf(base))183 ownKeys(base).forEach(key => {184 if (key === DRAFT_STATE) {185 return // Never copy over draft state.186 }187 const desc = Object.getOwnPropertyDescriptor(base, key)!188 let {value} = desc189 if (desc.get) {190 if (!invokeGetters) {191 throw new Error("Immer drafts cannot have computed properties")192 }193 value = desc.get.call(base)194 }195 if (desc.enumerable) {196 clone[key] = value197 } else {198 Object.defineProperty(clone, key, {199 value,200 writable: true,201 configurable: true202 })203 }204 })205 return clone

Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0

lines 206–223why, one step back
206}
207208export function freeze<T extends Objectish>(209 obj: T,210 deep: boolean = false211): void {212 if (!isDraftable(obj) || isDraft(obj) || Object.isFrozen(obj)) return213 if (isSet(obj)) {214 obj.add = obj.clear = obj.delete = dontMutateFrozenCollections as any215 } else if (isMap(obj)) {216 obj.set = obj.clear = obj.delete = dontMutateFrozenCollections as any217 }218 Object.freeze(obj)219 if (deep) each(obj, (_, value) => freeze(value, true))220}221222function dontMutateFrozenCollections() {223 throw new Error("This object has been frozen and should not be mutated")

TS type improvementsMichel Weststratebefore adoptiondd1808e

lines 224–239why, one step back
224}
225226export function createHiddenProperty(227 target: AnyObject,228 prop: PropertyKey,229 value: any230) {231 Object.defineProperty(target, prop, {232 value: value,233 enumerable: false,234 writable: true235 })236}237238export function die(): never {239 throw new Error("Illegal state, please file a bug")

Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0

line 240why, one step back
240}