Port an R Ledger
Lesson 47 of 48 in Coddy's JavaScript for R Developers course.
Challenge
EasyPort the accompanying R reference program to JavaScript. Input is an array of [name,quantity] pairs; names are strings and quantities are integers. Sum quantities by name, retain only positive totals, sort names by ASCII order, and return [name,total] pairs. Use a Map so prototype-like names work. Names contain only ASCII characters.
Reference program in R. Its contract-specific JSON adapter keeps ASCII names as byte values, including embedded NUL, and uses hexadecimal environment keys for safe lookup and ASCII sorting. Double values preserve the documented safe integer totals. It reads one JSON value and prints JSON.
# Narrow JSON adapter for well-formed arrays of [ASCII name, integer] pairs.
# Names stay as byte values, so embedded NUL does not become an R string.
text <- paste(readLines(file("stdin"),warn=FALSE),collapse="\n")
input <- utf8ToInt(text)
position <- 1L
peek <- function() if(position<=length(input)) input[position] else -1L
space <- function() {
while(peek() %in% c(9L,10L,13L,32L)) position <<- position+1L
}
take <- function(value) {
space()
stopifnot(peek()==value)
position <<- position+1L
}
read_name <- function() {
take(34L)
bytes <- integer()
repeat {
byte <- peek()
stopifnot(byte>=0L)
position <<- position+1L
if(byte==34L) break
if(byte==92L) {
kind <- peek()
position <<- position+1L
if(kind==117L) {
digits <- intToUtf8(input[position:(position+3L)])
byte <- strtoi(digits,base=16L)
stopifnot(!is.na(byte),byte<=127L)
position <<- position+4L
} else {
kinds <- c(34L,92L,47L,98L,102L,110L,114L,116L)
decoded <- c(34L,92L,47L,8L,12L,10L,13L,9L)
at <- match(kind,kinds)
stopifnot(!is.na(at))
byte <- decoded[at]
}
}
stopifnot(byte<=127L)
bytes <- c(bytes,byte)
}
bytes
}
read_quantity <- function() {
space()
remaining <- intToUtf8(input[position:length(input)])
token <- regmatches(remaining,regexpr("^-?[0-9]+(\\.[0-9]+)?([eE][+-]?[0-9]+)?",remaining))
stopifnot(length(token)==1L,nchar(token)>0L)
position <<- position+nchar(token)
value <- as.numeric(token)
stopifnot(is.finite(value),value==floor(value),abs(value)<=9007199254740991)
value
}
quote_name <- function(bytes) {
pieces <- character()
short <- c('\\"','\\\\','\\b','\\f','\\n','\\r','\\t')
codes <- c(34L,92L,8L,12L,10L,13L,9L)
for(byte in bytes) {
at <- match(byte,codes)
part <- if(!is.na(at)) short[at] else if(byte<32L) sprintf('\\u%04x',byte) else intToUtf8(byte)
pieces <- c(pieces,part)
}
paste0('"',paste(pieces,collapse=""),'"')
}
totals <- new.env(hash=TRUE,parent=emptyenv())
names_by_key <- new.env(hash=TRUE,parent=emptyenv())
take(91L)
space()
if(peek()!=93L) {
repeat {
take(91L)
name <- read_name()
take(44L)
quantity <- read_quantity()
take(93L)
# Fixed-width hexadecimal preserves ASCII lexicographic ordering.
key <- paste0("k",paste(sprintf("%02x",name),collapse=""))
old <- if(exists(key,envir=totals,inherits=FALSE)) totals[[key]] else 0
totals[[key]] <- old+quantity
names_by_key[[key]] <- name
space()
if(peek()!=44L) break
position <- position+1L
}
}
take(93L)
space()
stopifnot(position>length(input))
result <- character()
for(key in sort(ls(totals,all.names=TRUE),method="radix")) {
if(totals[[key]]>0) {
result <- c(result,paste0('[',quote_name(names_by_key[[key]]),',',sprintf('%.0f',totals[[key]]),']'))
}
}
cat('[',paste(result,collapse=','),']\n',sep='')
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 R Developers
1First JavaScript
Run JavaScriptStrings and TemplatesBindings and Block ScopeNumbers and ConversionNull and UndefinedRecap: Receipt4Iteration Pipelines
While and Early ExitMap and FilterReduce with an Initial ValueSorting Without SurprisesRecap: Build a Ranking2Decisions and Flow
Strict EqualityTruth TestsBranches and TernariesLoop Values and IndexesRecap: Shipping Rules5Functions
Functions and ReturnsDefaults and OptionsRest and Spread CallsClosures and CallbacksRecap: Pricing Function8Composition and Dispatch
CompositionInheritance and SuperDuck TypingValue Equality by ContractRecap: Channel Routing3Collections
Arrays and MutationObjects as RecordsMap and SetCopies and DestructuringRecap: Inventory Counts6Errors and Modules
JSON and Input BoundariesThrow and CatchES Modules and ImportsValidate Runtime ValuesRecap: Validate a Batch9Project: Order Processor
Model an OrderApply Member PricingPractice on your own: Online JavaScript compiler