Port a Ruby Ledger
Lesson 47 of 48 in Coddy's JavaScript for Ruby Developers course.
Challenge
EasyPort the complete Ruby reference program below to JavaScript. Input is an array of [name, quantity] pairs. Names are ASCII strings and quantities are integers. Sum every update by name, including negative intermediate totals. Keep only positive final totals and return [name, total] pairs sorted by ASCII name order. Use a Map so prototype-like names work. All input quantities and intermediate totals stay within the JavaScript safe integer range. Empty input or no positive totals returns [].
The Ruby reference uses Hash.new(0), destructuring in each, select, and sort_by. Translate the contract using a JavaScript Map so prototype-like names remain ordinary keys. Ruby Integer can grow, but this exercise restricts all inputs and intermediate totals to JavaScript safe integers. Names are ASCII and may include empty strings or prototype-like names. Aggregate first, filter positive totals afterward, and sort by name.
require "json"
def solve(rows)
totals = Hash.new(0)
rows.each do |name, quantity|
totals[name] += quantity
end
totals.select { |_, total| total > 0 }.sort_by { |name, _| name }
end
puts JSON.generate(solve(JSON.parse(STDIN.read)))Edit exercise.js and retain its solve export. The visible locked driver.js reads one JSON value, calls your function, and prints compact JSON with one final newline. Do not print inside solve.
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 Ruby Developers
1From Ruby to JavaScript
Run JavaScriptInterpolation and TemplatesRuby Locals to let and constIntegers to Numbernil, null, and undefinedRecap: Receipt4Enumerable to Array Pipelines
while, next, and continueEnumerable to Array Callbacksinject and Empty Reductionssort and Numeric ComparatorsRecap: Build a Ranking2Decisions and Flow
Equality Without CoercionTruthiness Beyond RubyBranches and Ternarieseach to for-ofRecap: Shipping Rules3Arrays, Hashes, and Maps
Array Mutation and Last ItemsHash Records to ObjectsHash, Map, and Setdup and Spread Are ShallowRecap: Inventory Counts6Errors and ES Modules
JSON at the Boundaryraise and rescue to throwrequire to ES ModulesRuntime Type ChecksRecap: Validate a Batch9Project: Order Processor
Model an OrderApply Member PricingPractice on your own: Online JavaScript compiler