From 172d91b31c553d035cb747fe2f569a00aa3d9f8f Mon Sep 17 00:00:00 2001 From: Andrew Huth Date: Wed, 10 Jan 2024 11:39:04 -0500 Subject: [PATCH] Add drop instruction and expand example --- src/cpu.ts | 11 +++++++++-- src/reducer.ts | 2 +- 2 files changed, 10 insertions(+), 3 deletions(-) diff --git a/src/cpu.ts b/src/cpu.ts index 9afc722..05e518c 100644 --- a/src/cpu.ts +++ b/src/cpu.ts @@ -34,6 +34,8 @@ export function parse(code: string): Instruction[] { output.push({op: 'add'}); } else if (trimmed === 'sub') { output.push({op: 'sub'}); + } else if (trimmed === 'drop') { + output.push({op: 'drop'}); } } @@ -42,12 +44,17 @@ export function parse(code: string): Instruction[] { export function execute(instruction: Instruction, stack: number[]): number[] { switch (instruction.op) { - case 'push': - return [instruction.operand, ...stack]; case 'add': { const [a, b, ...rest] = stack; return [a + b, ...rest]; } + case 'drop': { + // eslint-disable-next-line @typescript-eslint/no-unused-vars + const [_, ...rest] = stack; + return rest; + } + case 'push': + return [instruction.operand, ...stack]; case 'sub': { const [a, b, ...rest] = stack; return [a - b, ...rest]; diff --git a/src/reducer.ts b/src/reducer.ts index 277d9ed..801c1fb 100644 --- a/src/reducer.ts +++ b/src/reducer.ts @@ -2,7 +2,7 @@ import type {Dispatch as ReactDispatch} from 'react'; import {parse, execute, type Instruction} from './cpu'; export const initialState = { - code: 'push 1\npush 2\npush 3\nadd\nsub', + code: 'push 1\npush 2\npush 3\nadd\npush 4\nsub\nadd\ndrop', instructions: [] as Instruction[], onLine: null as number | null, stack: [] as number[],