Skip to content

Commit

Permalink
faster setIfDifferent
Browse files Browse the repository at this point in the history
  • Loading branch information
xaviergonz committed Mar 25, 2024
1 parent 251d686 commit 7b4e440
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 7 deletions.
8 changes: 4 additions & 4 deletions packages/lib/src/model/newModel.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,17 +6,17 @@ import { modelInfoByClass } from "../modelShared/modelInfo"
import { getInternalModelClassPropsInfo } from "../modelShared/modelPropsInfo"
import { applyModelInitializers } from "../modelShared/newModel"
import { getModelPropDefaultValue, noDefaultValue } from "../modelShared/prop"
import { Patch } from "../patch/Patch"
import { createPatchForObjectValueChange, emitPatches } from "../patch/emitPatch"
import { tweakModel } from "../tweaker/tweakModel"
import { tweakPlainObject } from "../tweaker/tweakPlainObject"
import { failure, inDevMode, makePropReadonly } from "../utils"
import { setIfDifferentWithReturn } from "../utils/setIfDifferent"
import type { AnyModel } from "./BaseModel"
import type { ModelConstructorOptions } from "./ModelConstructorOptions"
import { getModelIdPropertyName, getModelMetadata } from "./getModelMetadata"
import { modelTypeKey } from "./metadata"
import { assertIsModelClass } from "./utils"
import { setIfDifferent } from "../utils/setIfDifferent"
import { Patch } from "../patch/Patch"
import { emitPatches, createPatchForObjectValueChange } from "../patch/emitPatch"

/**
* @internal
Expand Down Expand Up @@ -131,7 +131,7 @@ export const internalNewModel = action(

if (modelIdPropertyName) {
const initialValue = initialData![modelIdPropertyName]
const valueChanged = setIfDifferent(initialData, modelIdPropertyName, id)
const valueChanged = setIfDifferentWithReturn(initialData, modelIdPropertyName, id)

if (valueChanged && mode === "fromSnapshot") {
const modelIdPath = [modelIdPropertyName]
Expand Down
10 changes: 7 additions & 3 deletions packages/lib/src/utils/setIfDifferent.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,13 @@
import { set } from "mobx"

export function setIfDifferent(target: any, key: PropertyKey, value: any): boolean {
const oldValue = target[key]
export function setIfDifferent(target: any, key: PropertyKey, value: unknown): void {
if (target[key] !== value || !(key in target)) {
set(target, key, value)
}
}

if (oldValue !== value || (value === undefined && !(key in target))) {
export function setIfDifferentWithReturn(target: any, key: PropertyKey, value: unknown): boolean {
if (target[key] !== value || !(key in target)) {
set(target, key, value)
return true
}
Expand Down

0 comments on commit 7b4e440

Please sign in to comment.