common.ts
This file
Path
src/common.ts
258 lines · 7.3 KiB · TypeScript
Last changed by
fixed most testsMichel Weststratebefore adoption385c0a4
History of this fileTake it
Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 1–107why, one step back1import {Objectish, ObjectishNoSet, ImmerState} from "./types"23/** 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.getOwnPropertyNames107added set and iteror stuffMichel Weststratebefore adoption08f4682
line 108why, one step back108// TODO: duplicate of clone? TODO: should be used by prepareCopy of map / setMerge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 109–149why, one step back109export function shallowCopy<T extends Objectish>(110 base: T,111 invokeGetters?: boolean112): T113export function shallowCopy(base, invokeGetters = false) {114 if (Array.isArray(base)) return base.slice()115 if (isMap(base)) return new Map(base)116 if (isSet(base)) return new Set(base)117 const clone = Object.create(Object.getPrototypeOf(base))118 ownKeys(base).forEach(key => {119 if (key === DRAFT_STATE) {120 return // Never copy over draft state.121 }122 const desc = Object.getOwnPropertyDescriptor(base, key)!123 let {value} = desc124 if (desc.get) {125 if (!invokeGetters) {126 throw new Error("Immer drafts cannot have computed properties")127 }128 value = desc.get.call(base)129 }130 if (desc.enumerable) {131 clone[key] = value132 } else {133 Object.defineProperty(clone, key, {134 value,135 writable: true,136 configurable: true137 })138 }139 })140 return clone141}142143export function each<T extends Objectish>(144 obj: T,145 iter: (key: PropertyKey, value: any, source: T) => void146)147export function each(obj, iter) {148 if (Array.isArray(obj) || isMap(obj) || isSet(obj)) {149 obj.forEach((entry, index) => iter(index, entry, obj))basic map tests succeedingMichel Weststratebefore adoption735c402
line 150why, one step back150 } else if (obj && typeof obj === "object") {Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
line 151why, one step back151 ownKeys(obj).forEach(key => iter(key, obj[key], obj))basic map tests succeedingMichel Weststratebefore adoption735c402
lines 152–153why, one step back152 } else {153 throw new Error("Cannot iterate primitive " + obj)Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 154–162why, one step back154 }155}156157export function isEnumerable(base: {}, prop: PropertyKey): boolean {158 const desc = Object.getOwnPropertyDescriptor(base, prop)159 return desc && desc.enumerable ? true : false160}161162export function has(thing: ObjectishNoSet, prop: PropertyKey): boolean {basic map tests succeedingMichel Weststratebefore adoption735c402
lines 163–165why, one step back163 return !thing164 ? false165 : isMap(thing)Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 166–196why, one step back166 ? thing.has(prop)167 : Object.prototype.hasOwnProperty.call(thing, prop)168}169170export function get(thing: ObjectishNoSet, prop: PropertyKey) {171 return isMap(thing) ? thing.get(prop) : thing[prop]172}173174export function is(x, y): boolean {175 // From: https://github.com/facebook/fbjs/blob/c69904a511b900266935168223063dd8772dfc40/packages/fbjs/src/core/shallowEqual.js176 if (x === y) {177 return x !== 0 || 1 / x === 1 / y178 } else {179 return x !== x && y !== y180 }181}182183export const hasSymbol = typeof Symbol !== "undefined"184185export const hasMap = typeof Map !== "undefined"186187export function isMap(target): target is Map<any, any> {188 return hasMap && target instanceof Map189}190191export const hasSet = typeof Set !== "undefined"192193export function isSet(target): target is Set<any> {194 return hasSet && target instanceof Set195}196fixed most testsMichel Weststratebefore adoption385c0a4
lines 197–204why, one step back197198export function makeIterable2(baseIterator: Iterator<any>): IterableIterator<any> {199 // TODO: correct?200 // TODO: don't use symbol201 baseIterator[Symbol.iterator] = () => baseIterator202 return baseIterator as any203}204Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 205–212why, one step back205export function makeIterable(next: () => {done: boolean; value: any}) {206 let self207 return (self = {208 [Symbol.iterator]: () => self,209 next210 })211}212map unification WIPMichel Weststratebefore adoption9bcefb6
line 213why, one step back213export function latest(state: any): any {Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 214–215why, one step back214 return state.copy || state.base215}fixed most testsMichel Weststratebefore adoption385c0a4
lines 216–228why, one step back216217// export function iterateCollection(collection: Map<any, any> | Set<any>, transformer: (key, value) => any) {218// // TODO: create own iterator symbols for fallback219// const iterator = collection.entries()220// return makeIterable(() => {221// const result = iterator.next()222// if (!result.done) {223// const value = wrapSetValue(state, result.value)224// result.value = isEntries ? [value, value] : value225// }226// return result227// } as any)228// }Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
line 229why, one step back229added set and iteror stuffMichel Weststratebefore adoption08f4682
line 230why, one step back230// TODO: duplicate of shallow cloneMerge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 231–258why, one step back231export function clone<T extends Objectish>(obj: T): T232export function clone(obj) {233 if (!isDraftable(obj)) return obj234 if (Array.isArray(obj)) return obj.map(clone)235 if (isMap(obj)) return new Map(obj)236 if (isSet(obj)) return new Set(obj)237 const cloned = Object.create(Object.getPrototypeOf(obj))238 for (const key in obj) cloned[key] = clone(obj[key])239 return cloned240}241242export function freeze<T extends Objectish>(243 obj: T,244 deep: boolean = false245): void {246 if (!isDraftable(obj) || isDraft(obj) || Object.isFrozen(obj)) return247 if (isSet(obj)) {248 obj.add = obj.clear = obj.delete = dontMutateFrozenCollections as any249 } else if (isMap(obj)) {250 obj.set = obj.clear = obj.delete = dontMutateFrozenCollections as any251 }252 Object.freeze(obj)253 if (deep) each(obj, (_, value) => freeze(value, true))254}255256function dontMutateFrozenCollections() {257 throw new Error("This object has been frozen and should not be mutated")258}