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 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}61TS type improvementsMichel Weststratebefore adoptiondd1808e
line 62why, one step back62export function isPlainObject(value: any): boolean {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–76why, one step back73 }74 // otherwise return undefined75}76TS type improvementsMichel Weststratebefore adoptiondd1808e
line 77why, one step back77export const ownKeys: (target: AnyObject) => PropertyKey[] =Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 78–81why, one step back78 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) => voidTS type improvementsMichel Weststratebefore adoptiondd1808e
lines 90–91why, one step back90): void91export function each(obj: any, iter: any) {Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
line 92why, one step back92 if (Array.isArray(obj) || isMap(obj) || isSet(obj)) {TS type improvementsMichel Weststratebefore adoptiondd1808e
line 93why, one step back93 obj.forEach((entry: any, index: any) => 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 {TS type improvementsMichel Weststratebefore adoptiondd1808e
line 97why, one step back97 die()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–105why, one step back102 const desc = Object.getOwnPropertyDescriptor(base, prop)103 return desc && desc.enumerable ? true : false104}105TS type improvementsMichel Weststratebefore adoptiondd1808e
lines 106–107why, one step back106// 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 back108export function has(thing: ObjectishNoSet, prop: PropertyKey): boolean {basic map tests succeedingMichel Weststratebefore adoption735c402
lines 109–111why, one step back109 return !thing110 ? false111 : isMap(thing)Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 112–115why, one step back112 ? thing.has(prop)113 : Object.prototype.hasOwnProperty.call(thing, prop)114}115TS type improvementsMichel Weststratebefore adoptiondd1808e
lines 116–118why, one step back116// 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 back119}120TS type improvementsMichel Weststratebefore adoptiondd1808e
lines 121–149why, one step back121// TODO: measure fast vs slow path, use type switch instead122export 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}149Further cleanup in progressMichel Weststratebefore adoptionaeba1ff
line 150why, one step back150export function is(x: any, y: any): boolean {Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 151–162why, one step back151 // From: https://github.com/facebook/fbjs/blob/c69904a511b900266935168223063dd8772dfc40/packages/fbjs/src/core/shallowEqual.js152 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"162Further cleanup in progressMichel Weststratebefore adoptionaeba1ff
line 163why, one step back163export function isMap(target: any): target is AnyMap {Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 164–168why, one step back164 return hasMap && target instanceof Map165}166167export const hasSet = typeof Set !== "undefined"168Further cleanup in progressMichel Weststratebefore adoptionaeba1ff
line 169why, one step back169export function isSet(target: any): target is AnySet {Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 170–172why, one step back170 return hasSet && target instanceof Set171}172Further cleanup in progressMichel Weststratebefore adoptionaeba1ff
line 173why, one step back173export function latest(state: ImmerState): any {Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 174–175why, one step back174 return state.copy || state.base175}fixed most testsMichel Weststratebefore adoption385c0a4
line 176why, one step back176Further cleanup in progressMichel Weststratebefore adoptionaeba1ff
line 177why, one step back177export function shallowCopy<T extends AnyObject | AnyArray>(Some initial cleanupMichel Weststratebefore adoptionc53a75f
lines 178–180why, one step back178 base: T,179 invokeGetters?: boolean180): TTS type improvementsMichel Weststratebefore adoptiondd1808e
line 181why, one step back181export function shallowCopy(base: any, invokeGetters = false) {Some initial cleanupMichel Weststratebefore adoptionc53a75f
lines 182–206why, one step back182 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 cloneMerge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 207–224why, one step back207}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 back225}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 back241}