common.ts
This file
Path
src/common.ts
216 lines · 6.0 KiB · TypeScript
Last changed by
Some initial cleanupMichel Weststratebefore adoptionc53a75f
History of this fileTake it
Some initial cleanupMichel Weststratebefore adoptionc53a75f
line 1why, one step back1import {Objectish, ObjectishNoSet} from "./types"Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 2–114why, one step back23/** Use a class type for `nothing` so its type is unique */4export class Nothing {5 // This lets us do `Exclude<T, Nothing>`6 // TODO: do this better, use unique symbol instead7 private _: any8}910/**11 * The sentinel value returned by producers to replace the draft with undefined.12 */13export const NOTHING: Nothing =14 typeof Symbol !== "undefined"15 ? Symbol("immer-nothing")16 : ({["immer-nothing"]: true} as any)1718/**19 * To let Immer treat your class instances as plain immutable objects20 * (albeit with a custom prototype), you must define either an instance property21 * or a static property on each of your custom classes.22 *23 * Otherwise, your class instance will never be drafted, which means it won't be24 * safe to mutate in a produce callback.25 */26export const DRAFTABLE: unique symbol =27 typeof Symbol !== "undefined" && Symbol.for28 ? Symbol.for("immer-draftable")29 : ("__$immer_draftable" as any)3031export const DRAFT_STATE: unique symbol =32 typeof Symbol !== "undefined" && Symbol.for33 ? Symbol.for("immer-state")34 : ("__$immer_state" as any)3536/** Returns true if the given value is an Immer draft */37export function isDraft(value: any): boolean {38 return !!value && !!value[DRAFT_STATE]39}4041/** Returns true if the given value can be drafted by Immer */42export function isDraftable(value: any): boolean {43 if (!value) return false44 return (45 isPlainObject(value) ||46 !!value[DRAFTABLE] ||47 !!value.constructor[DRAFTABLE] ||48 isMap(value) ||49 isSet(value)50 )51}5253export function isPlainObject(value): boolean {54 if (!value || typeof value !== "object") return false55 if (Array.isArray(value)) return true56 const proto = Object.getPrototypeOf(value)57 return !proto || proto === Object.prototype58}5960/** Get the underlying object that is represented by the given draft */61export function original<T>(value: T): T | undefined {62 if (value && value[DRAFT_STATE]) {63 return value[DRAFT_STATE].base64 }65 // otherwise return undefined66}6768// We use Maps as `drafts` for Sets, not Objects69// See proxy.js70export function assignSet(target: Map<any, any>, override) {71 override.forEach(value => {72 // When we add new drafts we have to remove their originals if present73 const prev = original(value)74 if (prev) target.delete(prev)75 // @ts-ignore TODO investigate76 target.add(value)77 })78 return target79}8081// We use Maps as `drafts` for Maps, not Objects82// See proxy.js83export function assignMap(target: Map<any, any>, override: Map<any, any>) {84 override.forEach((value, key) => target.set(key, value))85 return target86}8788export const assign =89 Object.assign ||90 ((target, ...overrides) => {91 overrides.forEach(override => {92 if (typeof override === "object" && override !== null)93 Object.keys(override).forEach(key => (target[key] = override[key]))94 })95 return target96 })9798export const ownKeys: (target) => PropertyKey[] =99 typeof Reflect !== "undefined" && Reflect.ownKeys100 ? Reflect.ownKeys101 : typeof Object.getOwnPropertySymbols !== "undefined"102 ? obj =>103 Object.getOwnPropertyNames(obj).concat(Object.getOwnPropertySymbols(104 obj105 ) as any)106 : Object.getOwnPropertyNames107108export function each<T extends Objectish>(109 obj: T,110 iter: (key: PropertyKey, value: any, source: T) => void111)112export function each(obj, iter) {113 if (Array.isArray(obj) || isMap(obj) || isSet(obj)) {114 obj.forEach((entry, index) => iter(index, entry, obj))basic map tests succeedingMichel Weststratebefore adoption735c402
line 115why, one step back115 } else if (obj && typeof obj === "object") {Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
line 116why, one step back116 ownKeys(obj).forEach(key => iter(key, obj[key], obj))basic map tests succeedingMichel Weststratebefore adoption735c402
lines 117–118why, one step back117 } else {118 throw new Error("Cannot iterate primitive " + obj)Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 119–127why, one step back119 }120}121122export function isEnumerable(base: {}, prop: PropertyKey): boolean {123 const desc = Object.getOwnPropertyDescriptor(base, prop)124 return desc && desc.enumerable ? true : false125}126127export function has(thing: ObjectishNoSet, prop: PropertyKey): boolean {basic map tests succeedingMichel Weststratebefore adoption735c402
lines 128–130why, one step back128 return !thing129 ? false130 : isMap(thing)Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 131–161why, one step back131 ? thing.has(prop)132 : Object.prototype.hasOwnProperty.call(thing, prop)133}134135export function get(thing: ObjectishNoSet, prop: PropertyKey) {136 return isMap(thing) ? thing.get(prop) : thing[prop]137}138139export function is(x, y): boolean {140 // From: https://github.com/facebook/fbjs/blob/c69904a511b900266935168223063dd8772dfc40/packages/fbjs/src/core/shallowEqual.js141 if (x === y) {142 return x !== 0 || 1 / x === 1 / y143 } else {144 return x !== x && y !== y145 }146}147148export const hasSymbol = typeof Symbol !== "undefined"149150export const hasMap = typeof Map !== "undefined"151152export function isMap(target): target is Map<any, any> {153 return hasMap && target instanceof Map154}155156export const hasSet = typeof Set !== "undefined"157158export function isSet(target): target is Set<any> {159 return hasSet && target instanceof Set160}161map unification WIPMichel Weststratebefore adoption9bcefb6
line 162why, one step back162export function latest(state: any): any {Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 163–164why, one step back163 return state.copy || state.base164}fixed most testsMichel Weststratebefore adoption385c0a4
line 165why, one step back165Some initial cleanupMichel Weststratebefore adoptionc53a75f
lines 166–197why, one step back166export function shallowCopy<T extends Objectish>(167 base: T,168 invokeGetters?: boolean169): T170export function shallowCopy(base, invokeGetters = false) {171 if (Array.isArray(base)) return base.slice()172 if (isMap(base)) return new Map(base)173 if (isSet(base)) return new Set(base)174 const clone = Object.create(Object.getPrototypeOf(base))175 ownKeys(base).forEach(key => {176 if (key === DRAFT_STATE) {177 return // Never copy over draft state.178 }179 const desc = Object.getOwnPropertyDescriptor(base, key)!180 let {value} = desc181 if (desc.get) {182 if (!invokeGetters) {183 throw new Error("Immer drafts cannot have computed properties")184 }185 value = desc.get.call(base)186 }187 if (desc.enumerable) {188 clone[key] = value189 } else {190 Object.defineProperty(clone, key, {191 value,192 writable: true,193 configurable: true194 })195 }196 })197 return cloneMerge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 198–216why, one step back198}199200export function freeze<T extends Objectish>(201 obj: T,202 deep: boolean = false203): void {204 if (!isDraftable(obj) || isDraft(obj) || Object.isFrozen(obj)) return205 if (isSet(obj)) {206 obj.add = obj.clear = obj.delete = dontMutateFrozenCollections as any207 } else if (isMap(obj)) {208 obj.set = obj.clear = obj.delete = dontMutateFrozenCollections as any209 }210 Object.freeze(obj)211 if (deep) each(obj, (_, value) => freeze(value, true))212}213214function dontMutateFrozenCollections() {215 throw new Error("This object has been frozen and should not be mutated")216}