Menu
CoddyTech

Port a Ruby Ledger

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

challenge icon

Challenge

Easy

Port 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

Practice on your own: Online JavaScript compiler