docs: refresh project rules and README for current engine API

This commit is contained in:
2026-04-25 04:36:53 +02:00
parent fbbc9455fb
commit 197cbb161c
2 changed files with 288 additions and 132 deletions
+63 -31
View File
@@ -1,20 +1,24 @@
# Project rules — RPN Virtual Calculator # Project rules — RPN Virtual Calculator
- Build a browser-friendly RPN calculator as a JavaScript class, preferably in a single file. - Build a browser-friendly RPN calculator as a JavaScript class, currently implemented in `src/rpn-calculator.js`.
- Keep code names, categories, and API identifiers in English. - Keep code names, categories, and API identifiers in English.
- Use only read-only / generic public API methods: `push`, `pop`, `clear`, `swap(index1, index2)`, `remove(index)`, `edit(index)`, `isValidIndex(index)`, `input(command)`, and `command(name, ...args)`. - Keep the public calculator API centered on the generic methods `push`, `pop`, `clear`, `swap(index1, index2)`, `remove(index)`, `edit(index)`, `isValidIndex(index)`, `input(command)`, and `command(name, ...args)`.
- Expose `inputValue` as a string and `isEditing` as a boolean. - `inputValue` must remain a string and `isEditing` must remain a boolean.
- Constructor options: - Keep constructor options aligned with the current engine:
- `maxSize` (default `2048`) - `maxSize` (default `2048`)
- `base` (default `10`) - `base` (default `10`, accepted range `2..16`)
- `angleMode` (`deg` default; also `rad` and `grad`) - `angleMode` (`deg` by default; also `rad` and `grad`)
- `enabledCommands` - `enabledCommands`
- Available constants: `pi`, `e`. - Available constants are `pi` and `e`.
- Supported operations must be centralized in one dictionary containing at least: - Supported operations must stay centralized in one dictionary containing at least:
- `argCount` - `argCount`
- `category` - `category`
- `aliases` - `aliases`
- Allowed categories are limited to: `Stack`, `Arithmetic`, and `Trigonometry`. - `execute`
- Allowed operation categories are limited to `Stack`, `Arithmetic`, and `Trigonometry`.
- The engine currently exposes static helpers for category discovery: `getOperationCategories()` and `getOperationsByCategory()`.
- The instance currently exposes `getOperationsByCategory()` and `getConstants()` helpers in addition to the generic API.
- Preserve browser and CommonJS exports for `RpnCalculator`.
## Supported commands ## Supported commands
@@ -22,42 +26,70 @@
- `add`, `sub`, `mul`, `div`, `mod`, `pow`, `sqr`, `neg`, `sqrt`, `recip`, - `add`, `sub`, `mul`, `div`, `mod`, `pow`, `sqr`, `neg`, `sqrt`, `recip`,
`sin`, `cos`, `tan`, `asin`, `acos`, `atan`, `log`, `ln`, `sin`, `cos`, `tan`, `asin`, `acos`, `atan`, `log`, `ln`,
`dup`, `drop`, `swap`, `clear`, `enter` `dup`, `drop`, `swap`, `clear`, `enter`
- Aliases: - Current aliases include:
- `+`, `-`, `*`, `/`, `%`, `^`, `y^x`, `1/x` - `+`, `-`, `*`, `/`, `%`, `^`, `y^x`, `1/x`
- Existing extra alias also present in code:
- `sqrt(x)` for `sqrt`
## Behavior rules ## Behavior rules
- `mod` is the percentage operator: `a b % => (a * b) / 100` - `mod` is the percentage operator: `a b % => (a * b) / 100`.
- `sqrt`, `asin`, `acos`, `log`, and `ln` must throw clear, explicit domain errors - `div` and `recip` must throw `Division by zero` on zero divisors.
- `log` uses `Math.log10` - `sqrt`, `asin`, `acos`, `log`, and `ln` must throw explicit domain errors.
- `ln` uses `Math.log` - `log` uses `Math.log10`.
- Trigonometric functions must support `deg`, `rad`, and `grad` - `ln` uses `Math.log`.
- In the browser demo, degrees are the default angle mode - Trigonometric functions must support `deg`, `rad`, and `grad`.
- `inputValue` must remain a string to preserve future hexadecimal input support - Direct trigonometric functions convert input angles with `toRadians(...)`.
- Inverse trigonometric functions convert results back using the current angle mode via `toDegrees(...)`.
- The engine rounds formatted numeric results to 12 decimal places and normalizes `-0` to `0`.
- `inputValue` must remain a string to preserve future hexadecimal-style input support.
- `parseInputValue(...)` currently uses `Number(...)` in base 10 and `parseInt(..., base)` for other bases.
- `input(command)` currently accepts single-character numeric editing input, including `0-9`, `A-F`, `a-f`, `+`, `-`, and `.`.
- `command(name, ...args)` currently resolves aliases, supports constants, commits pending input before execution, checks `enabledCommands`, and throws clear `Unknown command`, `Command disabled`, `Stack overflow`, `Stack underflow`, `Invalid stack index`, `Invalid number`, and `Invalid input value` errors where appropriate.
## Demo rules ## Demo rules
- The browser demo lives under `samples/dev/` - The active browser demo lives under `samples/dev/`.
- `samples/dev/index.html` is the demo entry page - `samples/dev/index.html` is the demo entry page.
- `samples/dev/index.css` contains the calculator visual theme - `samples/dev/index.css` contains the calculator visual theme.
- `samples/dev/index.js` contains demo-side presentation helpers and UI logic - `samples/dev/index.js` contains demo-side presentation helpers and UI logic.
- The demo UI must expose: - The demo currently exposes:
- a stack display - a stack display with four visible lines
- a main display - a main display/status area
- a visible angle mode indicator - a visible angle mode indicator
- an angle mode selector for `deg`, `rad`, and `grad` - an angle mode selector for `deg`, `rad`, and `grad`
- The demo may present user-facing labels such as `+`, ``, `×`, `÷`, `y^x`, `1/x`, and `x²` while still using English command identifiers internally - status pills showing `inputValue` and `isEditing`
- The example HTML must group buttons by `Stack`, `Arithmetic`, and `Trigonometry` - grouped command panels for `Stack`, `Arithmetic`, `Trigonometry`, and `Constants`
- The example HTML must call `command(...)` for actions - an error display area
- Keyboard support in the demo should remain consistent with the displayed help text - The demo may present user-facing labels such as `+`, ``, `×`, `÷`, `y^x`, `1/x`, and `x²` while still using English command identifiers internally.
- The example HTML groups buttons by `Stack`, `Arithmetic`, and `Trigonometry`, plus a dedicated `Constants` section.
- Demo buttons are wired through demo helpers that eventually call `command(...)` for calculator commands.
- The demo default angle mode is degrees.
- Keyboard support in the demo must remain consistent with the displayed help text.
- The current demo keyboard behavior supports:
- digits and decimal point
- numpad digits and numpad arithmetic keys
- `Enter` to validate input or toggle stack-item move mode
- `Backspace` to edit input or drop from the stack
- `Delete` to clear
- `Escape` to cancel editing, cancel move mode, or clear selection
- `ArrowUp` / `ArrowDown` to navigate or move selected stack items
- `ArrowRight` for swap
- `+`, `-`, `*`, `/`, `%`, `^`
- `q`, `n`, `r`, `i`, `g`, `l`, `s`, `c`, `S`, `C`
- `x`, `y`, `z`, `t` to select visible stack registers
- The demo currently implements stack selection and stack-item move mode in its own UI logic using the public stack methods.
- The demo currently duplicates X on `enter` when not editing, matching classic RPN-style behavior in the UI layer.
## File references ## File references
- `samples/dev/index.html` references `src/rpn-calculator.js` as the calculator engine used by the demo - `samples/dev/index.html` references `../../src/rpn-calculator.js` as the calculator engine used by the demo.
- Keep the demo aligned with the public calculator API exposed by `src/rpn-calculator.js` - Keep the demo aligned with the public calculator API exposed by `src/rpn-calculator.js`.
- `README.md` is currently outdated and duplicated in places; if documentation work is done later, align it with the actual engine and demo behavior.
## Maintenance ## Maintenance
- Re-read `src/rpn-calculator.js` and `samples/dev/` before updating these rules after project changes.
- Keep this file updated after each project change using the provided editing tools. - Keep this file updated after each project change using the provided editing tools.
- When changing the demo UI or calculator API, update these rules so they continue to match the current project behavior. - When changing the demo UI, keyboard help, exported API, command metadata, or calculator behavior, update these rules so they continue to match the current project behavior.
+225 -101
View File
@@ -2,87 +2,122 @@
A browser-friendly RPN calculator built around a small, generic JavaScript API. A browser-friendly RPN calculator built around a small, generic JavaScript API.
## Goal ## Overview
This project defines a reusable RPN calculator engine with: This project provides:
- a simple stack-based public API - a reusable JavaScript RPN engine in `src/rpn-calculator.js`
- configurable numeric and UI behavior - a browser demo in `samples/dev/`
- centralized command metadata - a command system centralized in a single operation dictionary
- a browser demo that uses the same public API as any consumer code - a small public API focused on stack operations and generic command dispatch
# RPN Virtual Calculator The main class is `RpnCalculator`.
A browser-friendly RPN calculator built around a small, generic JavaScript API.
## Goal
This project provides a reusable Reverse Polish Notation (RPN) calculator engine with:
- a simple stack-based public API
- configurable numeric behavior
- centralized command metadata
- browser demos that use the same public API as any consumer code
## Project structure ## Project structure
- `src/rpn-calculator.js`: calculator engine - `src/rpn-calculator.js`: calculator engine
- `samples/dev/index.html`: browser demo - `samples/dev/index.html`: active browser demo entry point
- `samples/calc-01/index.html`: browser demo - `samples/dev/index.css`: demo styles
- `samples/calc-XX/index.html`: browser demo - `samples/dev/index.js`: demo UI and keyboard logic
- `samples/calc-01/index.html`: active browser demo entry point
- `samples/calc-01/index.css`: demo styles
- `samples/calc-01/index.js`: demo UI and keyboard logic
- `samples/calc-XX/index.html`: active browser demo entry point
- `samples/calc-XX/index.css`: demo styles
- `samples/calc-XX/index.js`: demo UI and keyboard logic
## Main features ## Public API
- Single JavaScript class: `RpnCalculator` The calculator API is centered on these methods:
- Configurable stack size via `maxSize` (default: `2048`)
- Configurable numeric base via `base` (default: `10`) - `push(value)`
- Configurable angle mode via `angleMode`: - `pop()`
- `deg` (default) - `clear()`
- `rad` - `swap(index1, index2)`
- `grad` - `remove(index)`
- Optional command filtering through `enabledCommands` - `edit(index)`
- Public API limited to generic methods: - `isValidIndex(index)`
- `push(value)` - `input(command)`
- `pop()` - `command(name, ...args)`
- `clear()`
- `swap(index1, index2)` Instance helpers also available:
- `remove(index)`
- `edit(index)` - `getOperationsByCategory()`
- `isValidIndex(index)` - `getConstants()`
- `input(command)`
- `command(name, ...args)` Static helpers also available:
- `inputValue` is always stored as a string
- `isEditing` is exposed as a boolean - `RpnCalculator.getOperationCategories()`
- Supported operations are centralized in one dictionary with metadata such as: - `RpnCalculator.getOperationsByCategory()`
- `argCount`
- `category` State exposed on instances:
- `aliases`
- Supported categories are limited to: - `inputValue` as a string
- `Stack` - `isEditing` as a boolean
- `Arithmetic` - `stack` as the current internal stack array used by the demo
- `Trigonometry` - `angleMode`
## Available constants - `base`
- `maxSize`
## Constructor options
```js README.md
const calc = new RpnCalculator({
maxSize: 2048,
base: 10,
angleMode: 'deg',
enabledCommands: ['add', 'sub', 'mul', 'div']
});
```
Supported options:
- `maxSize`: maximum stack size, default `2048`
- `base`: numeric base, default `10`, accepted range `2..16`
- `angleMode`: `deg`, `rad`, or `grad`, default `deg`
- `enabledCommands`: optional whitelist of enabled commands and aliases
## Constants
Available constants:
- `pi` - `pi`
- `e` - `e`
They can be used through `command(...)`:
```js README.md
calc.command('pi');
calc.command('e');
```
## Supported commands ## Supported commands
### Stack
- `enter`
- `dup`
- `drop`
- `swap`
- `clear`
### Arithmetic ### Arithmetic
- `add` (`+`)
- `sub` (`-`) - `add` alias: `+`
- `mul` (`*`) - `sub` alias: `-`
- `div` (`/`) - `mul` alias: `*`
- `mod` (`%`) - `div` alias: `/`
- `pow` (`^`, `y^x`) - `mod` alias: `%`
- `pow` aliases: `^`, `y^x`
- `sqr` - `sqr`
- `neg` - `neg`
- `sqrt` - `sqrt` alias: `sqrt(x)`
- `recip` (`1/x`) - `recip` alias: `1/x`
- `log` - `log`
- `ln` - `ln`
### Trigonometry ### Trigonometry
- `sin` - `sin`
- `cos` - `cos`
- `tan` - `tan`
@@ -90,57 +125,146 @@ This project provides a reusable Reverse Polish Notation (RPN) calculator engine
- `acos` - `acos`
- `atan` - `atan`
### Stack ## Behavior notes
- `dup`
- `drop`
- `swap`
- `clear`
- `enter`
## Behavior rules
- `mod` is a percentage operator: - `mod` is a percentage operator:
- `a b % => (a * b) / 100` - `a b % => (a * b) / 100`
- `div` and `recip` throw `Division by zero` when needed
- `sqrt` throws `Invalid input for sqrt` for negative values
- `asin` and `acos` throw explicit domain errors outside `[-1, 1]`
- `log` throws `Invalid input for log` for values `<= 0`
- `ln` throws `Invalid input for ln` for values `<= 0`
- `log` uses `Math.log10` - `log` uses `Math.log10`
- `ln` uses `Math.log` - `ln` uses `Math.log`
- `sqrt`, `asin`, `acos`, `log`, and `ln` throw explicit domain errors on invalid input - direct trigonometric functions convert input using `toRadians(...)`
- Trigonometric behavior depends on `angleMode` - inverse trigonometric functions convert results back using the current angle mode
- In degree mode: - formatted numeric values are rounded to 12 decimal places
- `sin`, `cos`, `tan` convert degrees to radians internally - `-0` is normalized to `0`
- `asin`, `acos`, `atan` return degrees - `inputValue` remains a string to preserve future non-decimal input support
- `inputValue` remains a string to preserve future support for formats such as hexadecimal input - base 10 input is parsed with `Number(...)`
- non-decimal input currently uses `parseInt(..., base)`
## Input handling
`input(command)` supports two modes:
- single-character editing input
- command dispatch
Accepted single-character editing input currently includes:
- `0-9`
- `A-F`
- `a-f`
- `+`
- `-`
- `.`
Everything else is forwarded to `command(...)`.
## Basic usage ## Basic usage
### In a browser ### CommonJS
- `rpn-calculator.js`: calculator engine
- `rpn-example.html`: example browser interface
## Main features ```js README.md
- Single JavaScript class const RpnCalculator = require('./src/rpn-calculator');
- Configurable stack size (`maxSize`, default: `2048`)
- Configurable numeric base (`base`, default: `10`)
- Configurable angle mode (`angleMode`, default: `deg`)
- Optional command filtering through `enabledCommands`
- Generic public API centered on:
- `push`
- `pop`
- `clear`
- `swap(index1, index2)`
- `remove(index)`
- `edit(index)`
- `isValidIndex(index)`
- `input(command)`
- `command(name, ...args)`
- `inputValue` is kept as a string to preserve future input formats
- `isEditing` is exposed as a boolean state
- All supported commands are described in one centralized dictionary
- Supported categories are limited to:
- `Stack`
- `Arithmetic`
- `Trigonometry`
## Basic usage const calc = new RpnCalculator();
calc.push(2);
calc.push(3);
calc.command('add');
### In a browser console.log(calc.pop()); // 5
```
### Browser
```html README.md
<script src="./src/rpn-calculator.js"></script>
<script>
const calc = new RpnCalculator({ angleMode: 'deg' });
calc.push(9);
calc.command('sqrt');
console.log(calc.pop());
</script>
```
### Editing values through `input(...)`
```js README.md
const calc = new RpnCalculator();
calc.input('1');
calc.input('2');
calc.input('.');
calc.input('5');
calc.command('enter');
console.log(calc.pop()); // 12.5
```
### Aliases
```js README.md
const calc = new RpnCalculator();
calc.push(6);
calc.push(7);
calc.command('+');
console.log(calc.pop()); // 13
```
### Constants and trigonometry
```js README.md
const calc = new RpnCalculator({ angleMode: 'deg' });
calc.command('pi');
console.log(calc.pop());
calc.push(30);
calc.command('sin');
console.log(calc.pop()); // 0.5
```
## Demo
The active demo lives in `samples/dev/`.
Main UI features:
- four visible stack lines
- main display/status area
- visible angle mode indicator
- angle mode selector for `deg`, `rad`, and `grad`
- status pills for `inputValue` and `isEditing`
- grouped panels for `Stack`, `Arithmetic`, `Trigonometry`, and `Constants`
- error display area
The demo loads the engine from:
```html README.md
<script src="../../src/rpn-calculator.js"></script>
```
### Demo keyboard support
The current demo supports:
- digits and decimal point
- numpad digits and numpad arithmetic keys
- `Enter`
- `Backspace`
- `Delete`
- `Escape`
- `ArrowUp`, `ArrowDown`, `ArrowRight`
- `+`, `-`, `*`, `/`, `%`, `^`
- `q`, `n`, `r`, `i`, `g`, `l`, `s`, `c`, `S`, `C`
- `x`, `y`, `z`, `t`
The demo also implements stack selection and stack-item move mode in its UI layer using the public calculator methods.
## Exports
`RpnCalculator` is exposed in both environments:
- browser: `window.RpnCalculator`
- CommonJS: `module.exports = RpnCalculator`