Menu
CoddyTech

Final: Stock Ledger

Lesson 47 of 48 in Coddy's Rust for JavaScript Developers course.

challenge icon

Challenge

Medium

Port the complete JavaScript reference into the supplied Rust API. Input has up to 100 name delta rows, names lowercase ASCII words of at most 31 bytes and deltas from -1000 to 1000. Empty input is valid. Stock::new() -> Stock starts at zero; quantity(&self) -> i32 reads it; apply(&mut self, delta: i32) -> Result<(), &'static str> rejects a negative resulting quantity with Err("negative"), leaving state unchanged. Ledger::new() -> Ledger starts empty; its apply(&mut self, name: &str, delta: i32) has the same result contract, and must not create a missing item when rejecting. quantity(&self, name: &str) -> Option<i32> distinguishes missing from zero. report(&self) -> String lists only positive stocks as name:quantity in name order, separated by newlines, or empty. Return rejected:N, then the report on following lines. Calls to report do not change state. The JavaScript Map stores mutable Stock objects that any holder of a reference could change; Rust should own names and stocks. The reference sorts ASCII keys explicitly because JavaScript Map preserves insertion order.

Implement the required exported APIs and return the result from exercise::solve(input: &str) -> String without a final newline. Do not print in editable code. The locked driver checks required APIs independently, reads all stdin, and prints the returned text with one final newline.

Your code goes in exercise.rs, stock.rs, ledger.rs. main.rs holds the supplied input/output code and cannot be edited.

The JavaScript reference distinguishes a missing stock with undefined from a present zero. Its plain {ok, reason} result objects report failure without exceptions, and a rejected new item is never inserted. The stated integer bounds are safely exact for JavaScript number; Rust uses the specified integer types. Port the behavior into the required Rust modules.

Complete standalone JavaScript reference program:

// Standalone JavaScript reference for Node. No packages.
"use strict";

// A change result is {ok: true} or {ok: false, reason: "negative"}.
class Stock {
  #amount = 0;
  quantity() { return this.#amount; }
  apply(delta) {
    const next = this.#amount + delta;
    if (next < 0) return { ok: false, reason: "negative" };
    this.#amount = next;
    return { ok: true };
  }
}

class Ledger {
  #entries = new Map();
  apply(name, delta) {
    const existing = this.#entries.get(name);
    const stock = existing ?? new Stock();
    const result = stock.apply(delta);
    if (result.ok && existing === undefined) this.#entries.set(name, stock);
    return result;
  }
  quantity(name) {
    return this.#entries.get(name)?.quantity();
  }
  report() {
    const names = Array.from(this.#entries.keys()).sort();
    const rows = [];
    for (const name of names) {
      const stock = this.#entries.get(name);
      if (stock.quantity() > 0) rows.push(`${name}:${stock.quantity()}`);
    }
    return rows.length === 0 ? "empty" : rows.join("\n");
  }
}

function solve(input) {
  const ledger = new Ledger();
  let rejected = 0;
  const trimmed = input.trim();
  for (const line of trimmed === "" ? [] : trimmed.split(/\r?\n/)) {
    const [name, delta] = line.trim().split(/\s+/);
    if (!ledger.apply(name, Number(delta)).ok) rejected++;
  }
  return `rejected:${rejected}\n${ledger.report()}`;
}

module.exports = { Stock, Ledger, solve };

if (require.main === module) {
  process.stdout.write(solve(require("fs").readFileSync(0, "utf8")) + "\n");
}

Try it yourself

#![allow(dead_code, unused_imports, unused_variables, unused_mut)]
mod exercise;
mod stock;
mod ledger;
use std::io::{self, Read};
fn main() {
    let mut input=String::new();
    io::stdin().read_to_string(&mut input).unwrap();
    // BEGIN PUBLIC API PROBES
let mut s = stock::Stock::new(); assert_eq!(s.quantity(), 0);
    s.apply(11).unwrap(); assert_eq!(s.apply(-12), Err("negative")); assert_eq!(s.quantity(), 11);
    s.apply(-11).unwrap(); assert_eq!(s.quantity(), 0);
    let mut l = ledger::Ledger::new(); assert_eq!(l.quantity("held"), None);
    assert_eq!(l.apply("held", -8), Err("negative")); assert_eq!(l.quantity("held"), None);
    l.apply("held", 17).unwrap(); l.apply("alpha", 2).unwrap();
    assert_eq!(l.apply("held", -18), Err("negative")); assert_eq!(l.quantity("held"), Some(17));
    assert_eq!(l.report(), "alpha:2\nheld:17"); assert_eq!(l.report(), "alpha:2\nheld:17");
    l.apply("alpha", -2).unwrap(); assert_eq!(l.quantity("alpha"), Some(0)); assert_eq!(l.report(), "held:17");
    assert_eq!(ledger::Ledger::new().report(), "empty");
    // END PUBLIC API PROBES
    println!("{}", exercise::solve(&input));
}

All lessons in Rust for JavaScript Developers

Practice on your own: Online Rust compiler