Skip to content

Commit

Permalink
perf: expose internal api too KaboomCtx, avoid Array.find
Browse files Browse the repository at this point in the history
  • Loading branch information
lajbel committed May 26, 2024
1 parent c41c057 commit 379d06e
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 13 deletions.
21 changes: 8 additions & 13 deletions src/kaboom.ts
Original file line number Diff line number Diff line change
Expand Up @@ -160,6 +160,7 @@ import type {
GfxFont,
HealthComp,
ImageSource,
InternalCtx,
KaboomCtx,
KaboomOpt,
KaboomPlugin,
Expand Down Expand Up @@ -281,13 +282,7 @@ function createEmptyAudioBuffer(ctx: AudioContext) {
return ctx.createBuffer(1, 1, 44100);
}

type InternalContext = {
kaboomCtx: KaboomCtx;
getViewportScale: () => number;
};

let ctx: KaboomCtx;
let internalCtx: InternalContext[] = [];

// TODO: A better way to detect KaboomCtx
export const isKaboomCtx = (obj: any): obj is KaboomCtx => {
Expand All @@ -308,8 +303,8 @@ export const getKaboomContext = (fallBack?: any): KaboomCtx => {
return ctx;
};

export const getInternalContext = (kaboom: KaboomCtx): InternalContext => {
return internalCtx.find((ctx) => ctx.kaboomCtx === kaboom);
export const getInternalContext = (kaboom: KaboomCtx): InternalCtx => {
return kaboom._k;
};

// only exports one kaboom() which contains all the state
Expand Down Expand Up @@ -6615,9 +6610,14 @@ export default (gopt: KaboomOpt = {}): KaboomCtx => {

updateViewport();
initEvents();
const internalCtx = {
kaboomCtx: ctx,
getViewportScale,
};

// the exported ctx handle
ctx = {
_k: internalCtx,
VERSION,
// asset load
loadRoot,
Expand Down Expand Up @@ -6886,11 +6886,6 @@ export default (gopt: KaboomOpt = {}): KaboomCtx => {
EventController,
};

internalCtx.push({
kaboomCtx: ctx,
getViewportScale,
});

if (gopt.plugins) {
gopt.plugins.forEach(plug);
}
Expand Down
11 changes: 11 additions & 0 deletions src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,12 +36,23 @@ declare function kaboom<T extends PluginList<unknown> = [undefined]>(
options?: KaboomOpt<T>,
): T extends [undefined] ? KaboomCtx : KaboomCtx & MergePlugins<T>;

export type InternalCtx = {
kaboomCtx: KaboomCtx;
getViewportScale: () => number;
};

/**
* Context handle that contains every kaboom function.
*
* @group Start
*/
export interface KaboomCtx {
/**
* The internal context object.
*
* @private
*/
_k: InternalCtx;
/**
* Assemble a game object from a list of components, and add it to the game
*
Expand Down

0 comments on commit 379d06e

Please sign in to comment.