Skip to content

Commit

Permalink
Add drop instruction and expand example
Browse files Browse the repository at this point in the history
  • Loading branch information
ahuth committed Jan 10, 2024
1 parent 8a6db76 commit 172d91b
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 3 deletions.
11 changes: 9 additions & 2 deletions src/cpu.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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'});
}
}

Expand All @@ -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];
Expand Down
2 changes: 1 addition & 1 deletion src/reducer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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[],
Expand Down

0 comments on commit 172d91b

Please sign in to comment.