current.ts
This file
Path
src/core/current.ts
60 lines · 1.5 KiB · TypeScript
Last changed by
Immer 7Michel Weststratebefore adoption467ea5d
History of this fileTake it
Immer 7Michel Weststratebefore adoption467ea5d
lines 1–60why, one step back1import {2 die,3 isDraft,4 shallowCopy,5 each,6 DRAFT_STATE,7 get,8 set,9 ImmerState,10 isDraftable,11 ArchtypeMap,12 ArchtypeSet,13 getArchtype,14 getPlugin15} from "../internal"1617export function current<T>(value: T): T18export function current(value: any): any {19 if (!isDraft(value)) die(22, value)20 return currentImpl(value)21}2223function currentImpl(value: any): any {24 if (!isDraftable(value)) return value25 const state: ImmerState | undefined = value[DRAFT_STATE]26 let copy: any27 const archType = getArchtype(value)28 if (state) {29 if (30 !state.modified_ &&31 (state.type_ < 4 || !getPlugin("ES5").hasChanges_(state as any))32 )33 return state.base_34 // Optimization: avoid generating new drafts during copying35 state.finalized_ = true36 copy = copyHelper(value, archType)37 state.finalized_ = false38 } else {39 copy = copyHelper(value, archType)40 }4142 each(copy, (key, childValue) => {43 if (state && get(state.base_, key) === childValue) return // no need to copy or search in something that didn't change44 set(copy, key, currentImpl(childValue))45 })46 // In the future, we might consider freezing here, based on the current settings47 return archType === ArchtypeSet ? new Set(copy) : copy48}4950function copyHelper(value: any, archType: number): any {51 // creates a shallow copy, even if it is a map or set52 switch (archType) {53 case ArchtypeMap:54 return new Map(value)55 case ArchtypeSet:56 // Set will be cloned as array temporarily, so that we can replace individual items57 return Array.from(value)58 }59 return shallowCopy(value)60}