Port a Rust Ledger
Lesson 47 of 48 in Coddy's JavaScript for Rust Developers course.
Challenge
EasyPort the complete Rust reference below. Input is one JSON array of [name, quantity] pairs. Names contain only ASCII characters and quantities are integers. Sum every update by name, then retain only positive totals. Sort names by ASCII order and return [name, total] pairs. Use a JavaScript Map so names such as __proto__ remain ordinary data. All input numbers and intermediate integer totals stay within JavaScript's safe integer range.
The Rust reference includes a narrow JSON adapter for the documented ASCII-name and integer-pair input. It checks numeric tokens against the safe-integer range, accumulates with i64 and uses BTreeMap to retain ASCII key order, including empty names and embedded NUL. JavaScript Map supplies the data-key behavior, while Number is exact within the stated safe-integer bound. Map iteration order differs between the languages, so retain the explicit final sorting. The locked JavaScript driver owns JSON decoding and encoding.
use std::collections::BTreeMap;
use std::io::{self, Read};
// Contract-specific JSON adapter for well-formed [ASCII name, integer] pairs.
struct Reader<'a> { bytes: &'a [u8], position: usize }
impl<'a> Reader<'a> {
fn peek(&self) -> Option<u8> { self.bytes.get(self.position).copied() }
fn space(&mut self) {
while matches!(self.peek(), Some(b' ' | b'\t' | b'\n' | b'\r')) {
self.position += 1;
}
}
fn take(&mut self, byte: u8) {
self.space();
assert_eq!(self.peek(), Some(byte));
self.position += 1;
}
fn name(&mut self) -> String {
self.take(b'"');
let mut result = Vec::new();
loop {
let mut byte = self.peek().expect("unfinished name");
self.position += 1;
if byte == b'"' { break; }
if byte == b'\\' {
let kind = self.peek().expect("unfinished escape");
self.position += 1;
byte = match kind {
b'"' | b'\\' | b'/' => kind,
b'b' => 8, b'f' => 12, b'n' => 10, b'r' => 13, b't' => 9,
b'u' => {
let digits = std::str::from_utf8(&self.bytes[self.position..self.position+4]).unwrap();
let value = u16::from_str_radix(digits,16).unwrap();
assert!(value <= 127);
self.position += 4;
value as u8
}
_ => panic!("invalid escape"),
};
}
assert!(byte <= 127);
result.push(byte);
}
String::from_utf8(result).unwrap()
}
fn quantity(&mut self) -> i64 {
self.space();
let start = self.position;
while matches!(self.peek(), Some(b'0'..=b'9' | b'-' | b'+' | b'.' | b'e' | b'E')) {
self.position += 1;
}
let token = std::str::from_utf8(&self.bytes[start..self.position]).unwrap();
let number: f64 = token.parse().unwrap();
assert!(number.is_finite() && number.fract() == 0.0 && number.abs() <= 9007199254740991.0);
number as i64
}
}
fn quote(name: &str) -> String {
let mut output = String::from("\"");
for byte in name.bytes() {
match byte {
b'"' => output.push_str("\\\""),
b'\\' => output.push_str("\\\\"),
8 => output.push_str("\\b"), 12 => output.push_str("\\f"),
10 => output.push_str("\\n"), 13 => output.push_str("\\r"),
9 => output.push_str("\\t"),
0..=31 => output.push_str(&format!("\\u{:04x}",byte)),
_ => output.push(byte as char),
}
}
output.push('"');
output
}
fn main() {
let mut input = String::new();
io::stdin().read_to_string(&mut input).unwrap();
let mut reader = Reader { bytes: input.as_bytes(), position: 0 };
let mut totals: BTreeMap<String,i64> = BTreeMap::new();
reader.take(b'[');
reader.space();
if reader.peek() != Some(b']') {
loop {
reader.take(b'[');
let name = reader.name();
reader.take(b',');
let quantity = reader.quantity();
reader.take(b']');
*totals.entry(name).or_insert(0) += quantity;
reader.space();
if reader.peek() != Some(b',') { break; }
reader.position += 1;
}
}
reader.take(b']');
reader.space();
assert_eq!(reader.position, reader.bytes.len());
let rows: Vec<String> = totals.into_iter()
.filter(|(_,total)| *total > 0)
.map(|(name,total)| format!("[{},{}]",quote(&name),total))
.collect();
println!("[{}]",rows.join(","));
}
Edit exercise.js and keep its exported solve(input) API. The visible locked driver.js reads JSON and prints the return value as compact JSON followed by a newline. Do not add diagnostic output.
Try it yourself
import { readFileSync } from "node:fs";
import { solve } from "./exercise.js";
// One JSON value arrives on stdin. Return data; do not print inside solve.
const input = JSON.parse(readFileSync(0,"utf8"));
console.log(JSON.stringify(solve(input)));
All lessons in JavaScript for Rust Developers
1First JavaScript
Run JavaScriptFormatting and TemplatesDeclarations and RebindingInteger Types and NumberOption to Nullish ValuesRecap: Receipt4Iteration Pipelines
While and Early ExitLoops and Array CallbacksFolds and Empty ReductionsOrdering and Comparator SignsRecap: Build a Ranking2Decisions and Flow
Value and Identity EqualityBool Conditions and TruthinessIf and Conditional ValuesIterators and For-ofRecap: Shipping Rules3Collections
Vec and Array ObjectsStruct Fields and Own KeysMap, Set, and Key PresenceMoves, Clones, and SpreadRecap: Inventory Counts6Errors and Modules
JSON and Dynamic DataError Values Versus ExceptionsPackage Exports and ESMTypes and Runtime ChecksRecap: Validate a Batch9Project: Order Processor
Model an OrderApply Member PricingPractice on your own: Online JavaScript compiler