Skip to content

Commit

Permalink
refactor: replace JSON.parse with structureClone do clone context (
Browse files Browse the repository at this point in the history
  • Loading branch information
ortense authored Jan 15, 2024
1 parent 16f6f3e commit 57dc801
Show file tree
Hide file tree
Showing 3 changed files with 9 additions and 6 deletions.
5 changes: 5 additions & 0 deletions .changeset/chilled-boxes-walk.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@ortense/mediator": minor
---

replace `JSON.parse` with `structureClone` do clone context
8 changes: 3 additions & 5 deletions src/factory.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
import { Mediator, MediatorContext, MediatorEventListener } from './types.ts'

const freezeCopy = <T>(ctx: T): T => Object.freeze(JSON.parse(JSON.stringify(ctx)))

/**
* Creates a Mediator instance with a specific initial context.
* @function createMediator
Expand All @@ -25,7 +23,7 @@ export function createMediator <
EventName extends string = string,
>(initialContext: Context): Mediator<Context, EventName> {
const handlers = new Map<string, Array<MediatorEventListener<Context, EventName>>>()
let context = freezeCopy(initialContext)
let context = structuredClone(initialContext)

return {
on: (event, listener) => {
Expand All @@ -44,13 +42,13 @@ export function createMediator <

send: (event, modifier) => {
if(modifier) {
context = freezeCopy({ ...context, ...modifier(context) })
context = structuredClone({ ...context, ...modifier(context) })
}

handlers.get(event)?.forEach(fn => fn(context, event))
handlers.get('*')?.forEach(fn => fn(context, event))
},

getContext: () => freezeCopy(context),
getContext: () => structuredClone(context),
}
}
2 changes: 1 addition & 1 deletion src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ export type MediatorContextModifier<Context extends MediatorContext> = (ctx: Rea
* @template Context - The type of the MediatorContext.
* @template EventName - The type of the event names.
*/
export interface Mediator<Context extends MediatorContext, EventName extends string> {
export type Mediator<Context extends MediatorContext, EventName extends string> = {
/**
* Adds an event listener to the Mediator.
* @method
Expand Down

0 comments on commit 57dc801

Please sign in to comment.