Skip to content
Myr

common.ts

This file

Path

src/common.ts

241 lines · 6.3 KiB · TypeScript

Last changed by

TS type improvementsMichel Weststratebefore adoptiondd1808e

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–61why, 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}1819/**20 * The sentinel value returned by producers to replace the draft with undefined.21 */22export const NOTHING: Nothing =23 typeof Symbol !== "undefined"24 ? Symbol("immer-nothing")25 : ({["immer-nothing"]: true} as any)2627/**28 * To let Immer treat your class instances as plain immutable objects29 * (albeit with a custom prototype), you must define either an instance property30 * or a static property on each of your custom classes.31 *32 * Otherwise, your class instance will never be drafted, which means it won't be33 * safe to mutate in a produce callback.34 */35export const DRAFTABLE: unique symbol =36 typeof Symbol !== "undefined" && Symbol.for37 ? Symbol.for("immer-draftable")38 : ("__$immer_draftable" as any)3940export const DRAFT_STATE: unique symbol =41 typeof Symbol !== "undefined" && Symbol.for42 ? Symbol.for("immer-state")43 : ("__$immer_state" as any)4445/** Returns true if the given value is an Immer draft */46export function isDraft(value: any): boolean {47 return !!value && !!value[DRAFT_STATE]48}4950/** Returns true if the given value can be drafted by Immer */51export function isDraftable(value: any): boolean {52 if (!value) return false53 return (54 isPlainObject(value) ||55 !!value[DRAFTABLE] ||56 !!value.constructor[DRAFTABLE] ||57 isMap(value) ||58 isSet(value)59 )60}61

TS type improvementsMichel Weststratebefore adoptiondd1808e

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

Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0

lines 63–69why, one step back
63 if (!value || typeof value !== "object") return false
64 if (Array.isArray(value)) return true65 const proto = Object.getPrototypeOf(value)66 return !proto || proto === Object.prototype67}6869/** Get the underlying object that is represented by the given draft */

Dropped Object.assignMichel Weststratebefore adoption79a1d2c

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

Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0

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

Dropped Object.assignMichel Weststratebefore adoption79a1d2c

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

Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0

lines 73–76why, one step back
73 }
74 // otherwise return undefined75}76

TS type improvementsMichel Weststratebefore adoptiondd1808e

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

Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0

lines 78–81why, one step back
78 typeof Reflect !== "undefined" && Reflect.ownKeys
79 ? Reflect.ownKeys80 : typeof Object.getOwnPropertySymbols !== "undefined"81 ? obj =>

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

lines 82–84why, one step back
82 Object.getOwnPropertyNames(obj).concat(
83 Object.getOwnPropertySymbols(obj) as any84 )

Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0

lines 85–88why, one step back
85 : Object.getOwnPropertyNames
8687export function each<T extends Objectish>(88 obj: T,

Further cleanup in progressMichel Weststratebefore adoptionaeba1ff

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

TS type improvementsMichel Weststratebefore adoptiondd1808e

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

Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0

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

TS type improvementsMichel Weststratebefore adoptiondd1808e

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

basic map tests succeedingMichel Weststratebefore adoption735c402

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

Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0

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

basic map tests succeedingMichel Weststratebefore adoption735c402

line 96why, one step back
96 } else {

TS type improvementsMichel Weststratebefore adoptiondd1808e

line 97why, one step back
97 die()

Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0

lines 98–100why, one step back
98 }
99}100

Dropped Object.assignMichel Weststratebefore adoption79a1d2c

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

Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0

lines 102–105why, one step back
102 const desc = Object.getOwnPropertyDescriptor(base, prop)
103 return desc && desc.enumerable ? true : false104}105

TS type improvementsMichel Weststratebefore adoptiondd1808e

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

Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0

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

basic map tests succeedingMichel Weststratebefore adoption735c402

lines 109–111why, one step back
109 return !thing
110 ? false111 : isMap(thing)

Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0

lines 112–115why, one step back
112 ? thing.has(prop)
113 : Object.prototype.hasOwnProperty.call(thing, prop)114}115

TS type improvementsMichel Weststratebefore adoptiondd1808e

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

Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0

lines 119–120why, one step back
119}
120

TS type improvementsMichel Weststratebefore adoptiondd1808e

lines 121–149why, one step back
121// TODO: measure fast vs slow path, use type switch instead
122export function set(parent: Drafted, prop: PropertyKey, value: any) {123 // fast path switch on meta data124 if (parent[DRAFT_STATE])125 switch (parent[DRAFT_STATE].type) {126 case "map":127 parent.set(prop, value)128 break129 case "set":130 parent.delete(prop)131 parent.add(value)132 break133 default:134 parent[prop] = value135 }136137 // slow path138 parent[prop] = value139 if (isMap(parent)) {140 parent.set(prop, value)141 } else if (isSet(parent)) {142 // In this case, the `prop` is actually a draft.143 parent.delete(prop)144 parent.add(value)145 } else {146 parent[prop] = value147 }148}149

Further cleanup in progressMichel Weststratebefore adoptionaeba1ff

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

Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0

lines 151–162why, one step back
151 // From: https://github.com/facebook/fbjs/blob/c69904a511b900266935168223063dd8772dfc40/packages/fbjs/src/core/shallowEqual.js
152 if (x === y) {153 return x !== 0 || 1 / x === 1 / y154 } else {155 return x !== x && y !== y156 }157}158159export const hasSymbol = typeof Symbol !== "undefined"160161export const hasMap = typeof Map !== "undefined"162

Further cleanup in progressMichel Weststratebefore adoptionaeba1ff

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

Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0

lines 164–168why, one step back
164 return hasMap && target instanceof Map
165}166167export const hasSet = typeof Set !== "undefined"168

Further cleanup in progressMichel Weststratebefore adoptionaeba1ff

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

Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0

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

Further cleanup in progressMichel Weststratebefore adoptionaeba1ff

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

Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0

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

fixed most testsMichel Weststratebefore adoption385c0a4

line 176why, one step back
176

Further cleanup in progressMichel Weststratebefore adoptionaeba1ff

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

Some initial cleanupMichel Weststratebefore adoptionc53a75f

lines 178–180why, one step back
178 base: T,
179 invokeGetters?: boolean180): T

TS type improvementsMichel Weststratebefore adoptiondd1808e

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

Some initial cleanupMichel Weststratebefore adoptionc53a75f

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

Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0

lines 207–224why, one step back
207}
208209export function freeze<T extends Objectish>(210 obj: T,211 deep: boolean = false212): void {213 if (!isDraftable(obj) || isDraft(obj) || Object.isFrozen(obj)) return214 if (isSet(obj)) {215 obj.add = obj.clear = obj.delete = dontMutateFrozenCollections as any216 } else if (isMap(obj)) {217 obj.set = obj.clear = obj.delete = dontMutateFrozenCollections as any218 }219 Object.freeze(obj)220 if (deep) each(obj, (_, value) => freeze(value, true))221}222223function dontMutateFrozenCollections() {224 throw new Error("This object has been frozen and should not be mutated")

TS type improvementsMichel Weststratebefore adoptiondd1808e

lines 225–240why, one step back
225}
226227export function createHiddenProperty(228 target: AnyObject,229 prop: PropertyKey,230 value: any231) {232 Object.defineProperty(target, prop, {233 value: value,234 enumerable: false,235 writable: true236 })237}238239export function die(): never {240 throw new Error("Illegal state, please file a bug")

Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0

line 241why, one step back
241}