common.ts
This file
Path
src/common.ts
193 lines · 5.2 KiB · TypeScript
Last changed by
Further cleanup in progressMichel Weststratebefore adoptionaeba1ff
History of this fileTake it
Further cleanup in progressMichel Weststratebefore adoptionaeba1ff
lines 1–10why, one step back1import {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 back1112/** 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}61Dropped Object.assignMichel Weststratebefore adoption79a1d2c
line 62why, one step back62export function isPlainObject(value): value is AnyObject | AnyArray {Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 63–69why, one step back63 if (!value || typeof value !== "object") return false64 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 back70export function original<T>(value: Drafted<T>): T | undefined {Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
line 71why, one step back71 if (value && value[DRAFT_STATE]) {Dropped Object.assignMichel Weststratebefore adoption79a1d2c
line 72why, one step back72 return value[DRAFT_STATE].base as anyMerge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 73–81why, one step back73 }74 // otherwise return undefined75}7677export const ownKeys: (target) => PropertyKey[] =78 typeof Reflect !== "undefined" && Reflect.ownKeys79 ? Reflect.ownKeys80 : typeof Object.getOwnPropertySymbols !== "undefined"81 ? obj =>🎵...killing me softly, with your fingers... 🎶Michel Weststratebefore adoption19a6b66
lines 82–84why, one step back82 Object.getOwnPropertyNames(obj).concat(83 Object.getOwnPropertySymbols(obj) as any84 )Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 85–88why, one step back85 : Object.getOwnPropertyNames8687export function each<T extends Objectish>(88 obj: T,Further cleanup in progressMichel Weststratebefore adoptionaeba1ff
line 89why, one step back89 iter: (key: string | number, value: any, source: T) => voidMerge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 90–93why, one step back90)91export function each(obj, iter) {92 if (Array.isArray(obj) || isMap(obj) || isSet(obj)) {93 obj.forEach((entry, index) => iter(index, entry, obj))basic map tests succeedingMichel Weststratebefore adoption735c402
line 94why, one step back94 } else if (obj && typeof obj === "object") {Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
line 95why, one step back95 ownKeys(obj).forEach(key => iter(key, obj[key], obj))basic map tests succeedingMichel Weststratebefore adoption735c402
line 96why, one step back96 } else {🎵...killing me softly, with your fingers... 🎶Michel Weststratebefore adoption19a6b66
line 97why, one step back97 throw new Error("Nope")Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 98–100why, one step back98 }99}100Dropped Object.assignMichel Weststratebefore adoption79a1d2c
line 101why, one step back101export function isEnumerable(base: AnyObject, prop: PropertyKey): boolean {Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 102–106why, one step back102 const desc = Object.getOwnPropertyDescriptor(base, prop)103 return desc && desc.enumerable ? true : false104}105106export function has(thing: ObjectishNoSet, prop: PropertyKey): boolean {basic map tests succeedingMichel Weststratebefore adoption735c402
lines 107–109why, one step back107 return !thing108 ? false109 : isMap(thing)Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 110–113why, one step back110 ? thing.has(prop)111 : Object.prototype.hasOwnProperty.call(thing, prop)112}113Further cleanup in progressMichel Weststratebefore adoptionaeba1ff
line 114why, one step back114export function get(thing: ObjectishNoSet, prop: PropertyKey): any {Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 115–117why, one step back115 return isMap(thing) ? thing.get(prop) : thing[prop]116}117Further cleanup in progressMichel Weststratebefore adoptionaeba1ff
line 118why, one step back118export function is(x: any, y: any): boolean {Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 119–130why, one step back119 // From: https://github.com/facebook/fbjs/blob/c69904a511b900266935168223063dd8772dfc40/packages/fbjs/src/core/shallowEqual.js120 if (x === y) {121 return x !== 0 || 1 / x === 1 / y122 } else {123 return x !== x && y !== y124 }125}126127export const hasSymbol = typeof Symbol !== "undefined"128129export const hasMap = typeof Map !== "undefined"130Further cleanup in progressMichel Weststratebefore adoptionaeba1ff
line 131why, one step back131export function isMap(target: any): target is AnyMap {Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 132–136why, one step back132 return hasMap && target instanceof Map133}134135export const hasSet = typeof Set !== "undefined"136Further cleanup in progressMichel Weststratebefore adoptionaeba1ff
line 137why, one step back137export function isSet(target: any): target is AnySet {Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 138–140why, one step back138 return hasSet && target instanceof Set139}140Further cleanup in progressMichel Weststratebefore adoptionaeba1ff
line 141why, one step back141export function latest(state: ImmerState): any {Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 142–143why, one step back142 return state.copy || state.base143}fixed most testsMichel Weststratebefore adoption385c0a4
line 144why, one step back144Further cleanup in progressMichel Weststratebefore adoptionaeba1ff
line 145why, one step back145export function shallowCopy<T extends AnyObject | AnyArray>(Some initial cleanupMichel Weststratebefore adoptionc53a75f
lines 146–174why, one step back146 base: T,147 invokeGetters?: boolean148): T149export function shallowCopy(base, invokeGetters = false) {150 if (Array.isArray(base)) return base.slice()151 const clone = Object.create(Object.getPrototypeOf(base))152 ownKeys(base).forEach(key => {153 if (key === DRAFT_STATE) {154 return // Never copy over draft state.155 }156 const desc = Object.getOwnPropertyDescriptor(base, key)!157 let {value} = desc158 if (desc.get) {159 if (!invokeGetters) {160 throw new Error("Immer drafts cannot have computed properties")161 }162 value = desc.get.call(base)163 }164 if (desc.enumerable) {165 clone[key] = value166 } else {167 Object.defineProperty(clone, key, {168 value,169 writable: true,170 configurable: true171 })172 }173 })174 return cloneMerge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 175–193why, one step back175}176177export function freeze<T extends Objectish>(178 obj: T,179 deep: boolean = false180): void {181 if (!isDraftable(obj) || isDraft(obj) || Object.isFrozen(obj)) return182 if (isSet(obj)) {183 obj.add = obj.clear = obj.delete = dontMutateFrozenCollections as any184 } else if (isMap(obj)) {185 obj.set = obj.clear = obj.delete = dontMutateFrozenCollections as any186 }187 Object.freeze(obj)188 if (deep) each(obj, (_, value) => freeze(value, true))189}190191function dontMutateFrozenCollections() {192 throw new Error("This object has been frozen and should not be mutated")193}