Skip to content

Commit

Permalink
Use new Function instead of eval
Browse files Browse the repository at this point in the history
  • Loading branch information
hubol committed Feb 13, 2024
1 parent b8a4ed6 commit e9a14d3
Showing 1 changed file with 10 additions and 14 deletions.
24 changes: 10 additions & 14 deletions src/lib/game-engine/input/mapped-gamepad.ts
Original file line number Diff line number Diff line change
Expand Up @@ -105,25 +105,23 @@ interface GamepadConfig {
type CopyStateFn<T> = (current: T, previous: T) => void;

function compileCopyStateFn<T>(keys: string[]): CopyStateFn<T> {
return eval(`// Generated by src/lib/game-engine/input/mapped-gamepad.ts
return new Function('current', 'previous',
`// Generated by src/lib/game-engine/input/mapped-gamepad.ts
// compileCopyStateFn
function copyDownFn(current, previous) {
${keys.map(key => ` previous.${key} = current.${key};`).join('\n')}
}
copyDownFn`);
${keys.map(key => `previous.${key} = current.${key};`).join('\n')}`) as any
}

type ApplyGamepadToInputFn<TAction extends string> = (gamepad: Gamepad, state: Record<TAction, boolean>) => void;

function compileApplyGamepadToInput<TAction extends string>(controls: GamepadControls<TAction>, config: GamepadConfig): ApplyGamepadToInputFn<TAction> {
const axisUnitDistanceSquared = Math.pow(config.axisUnitDistance, 2);

return eval(`// Generated by src/lib/game-engine/input/mapped-gamepad.ts
return new Function('v1', 'v2', 'sqDistance',
`// Generated by src/lib/game-engine/input/mapped-gamepad.ts
// compileApplyGamepadToInput
function vectorContext(v1, v2, sqDistance) {
return function applyGamepadToState(gamepad, state) {
return function applyGamepadToState(gamepad, state) {
${Object.entries(controls).flatMap(([action, controls]) => {
return ` state.${action} = ${(controls as GamepadControlType[]).map(control => {
return ` state.${action} = ${(controls as GamepadControlType[]).map(control => {
switch (control.kind) {
case "button":
return `gamepad.buttons[${control.index}].pressed`;
Expand All @@ -135,9 +133,7 @@ ${Object.entries(controls).flatMap(([action, controls]) => {
throw new Error(`Unrecognized Control kind ${(control as any).kind}`);
}
}).join(`
|| `)};`;
}).join('\n')}
}
}
vectorContext`)(vnew(), vnew(), sqDistance);
|| `)};`;
}).join('\n')}
}`)(vnew(), vnew(), sqDistance);
}

0 comments on commit e9a14d3

Please sign in to comment.