Menu
CoddyTech

Port a C++ Ledger

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

challenge icon

Challenge

Easy

Port the C++ reference algorithm to JavaScript. Input is an array of [ASCII name,integer quantity] pairs. C++ uses a sorted std::map with string keys and 64-bit integer totals; JavaScript should aggregate with Map and sort explicitly. Return only positive totals as [name,total] pairs in ASCII name order. The companion C++ program runs three reference fixtures.

Reference program in C++. The complete program parses the stated JSON pair-array contract, including escaped ASCII names, and prints JSON.

#include <iostream>
#include <sstream>
#include <string>
#include <map>
#include <vector>
#include <cstdint>
#include <cctype>
#include <stdexcept>
#include <utility>

// This reader handles the stated array-of-pairs contract with ASCII names.
class Reader {
    std::string text;
    std::size_t pos=0;
    void whitespace() {
        while(pos<text.size() && std::isspace(static_cast<unsigned char>(text[pos]))) ++pos;
    }
    char take() {
        if(pos==text.size()) throw std::runtime_error("unexpected end");
        return text[pos++];
    }
    static unsigned hex(char c) {
        if(c>='0' && c<='9') return static_cast<unsigned>(c-'0');
        if(c>='a' && c<='f') return static_cast<unsigned>(c-'a'+10);
        if(c>='A' && c<='F') return static_cast<unsigned>(c-'A'+10);
        throw std::runtime_error("bad escape");
    }
public:
    explicit Reader(std::string input):text(std::move(input)) {}
    void token(char expected) {
        whitespace();
        if(take()!=expected) throw std::runtime_error("bad token");
    }
    bool next_is(char c) {
        whitespace();
        return pos<text.size() && text[pos]==c;
    }
    std::string name() {
        token('"');
        std::string result;
        for(;;) {
            unsigned value=static_cast<unsigned char>(take());
            if(value=='"') break;
            if(value=='\\') {
                switch(take()) {
                    case '"': value='"'; break;
                    case '\\': value='\\'; break;
                    case '/': value='/'; break;
                    case 'b': value='\b'; break;
                    case 'f': value='\f'; break;
                    case 'n': value='\n'; break;
                    case 'r': value='\r'; break;
                    case 't': value='\t'; break;
                    case 'u':
                        value=0;
                        for(int i=0;i<4;++i) value=value*16+hex(take());
                        break;
                    default: throw std::runtime_error("bad escape");
                }
            }
            if(value>127) throw std::runtime_error("non-ASCII name");
            result.push_back(static_cast<char>(value));
        }
        return result;
    }
    std::int64_t quantity() {
        whitespace();
        std::size_t consumed=0;
        double value=std::stod(text.substr(pos),&consumed);
        if(!(value>=-9007199254740991.0 && value<=9007199254740991.0))
            throw std::runtime_error("quantity out of bounds");
        auto integer=static_cast<std::int64_t>(value);
        if(static_cast<double>(integer)!=value) throw std::runtime_error("fractional quantity");
        pos+=consumed;
        return integer;
    }
    void finish() {
        whitespace();
        if(pos!=text.size()) throw std::runtime_error("extra input");
    }
};
static void print_name(const std::string& name) {
    const char *hex="0123456789abcdef";
    std::cout << '"';
    for(unsigned char c:name) {
        switch(c) {
            case '"': std::cout << "\\\""; break;
            case '\\': std::cout << "\\\\"; break;
            case '\b': std::cout << "\\b"; break;
            case '\f': std::cout << "\\f"; break;
            case '\n': std::cout << "\\n"; break;
            case '\r': std::cout << "\\r"; break;
            case '\t': std::cout << "\\t"; break;
            default:
                if(c<32) std::cout << "\\u00" << hex[c/16] << hex[c%16];
                else std::cout << static_cast<char>(c);
        }
    }
    std::cout << '"';
}
int main() {
    std::ostringstream input;
    input << std::cin.rdbuf();
    Reader reader(input.str());
    std::map<std::string,std::int64_t> totals;
    reader.token('[');
    if(!reader.next_is(']')) {
        do {
            reader.token('[');
            auto name=reader.name();
            reader.token(',');
            auto quantity=reader.quantity();
            reader.token(']');
            totals[name]+=quantity;
            if(!reader.next_is(',')) break;
            reader.token(',');
        } while(true);
    }
    reader.token(']');
    reader.finish();
    std::cout << '[';
    bool first=true;
    for(const auto& [name,total]:totals) {
        if(total<=0) continue;
        if(!first) std::cout << ',';
        first=false;
        std::cout << '[';
        print_name(name);
        std::cout << ',' << total << ']';
    }
    std::cout << "]\n";
}

Input is one JSON value. Edit the unlocked files, starting with exercise.js. The visible locked driver.js calls solve(input) and prints its return value as compact JSON followed by one newline. Do not add diagnostic output. Tests compare the full output. All number inputs and computed integer totals stay within the safe integer range.

Example input:

[["pen",3],["book",1],["pen",-1]]

Expected output:

[["book",1],["pen",2]]

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 C++ Developers

Practice on your own: Online JavaScript compiler