Port a C Ledger
Lesson 47 of 48 in Coddy's JavaScript for C Developers course.
Challenge
EasyPort the complete C 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 C reference includes a small parser for the stated JSON pair-array contract, decodes ASCII name escapes, and accumulates into signed 64-bit totals. Name lengths are tracked explicitly so even an escaped zero byte remains data. It sorts keys and emits JSON with string escaping. JavaScript Map supplies the data-key behavior, while Number is exact within the stated safe-integer bound. Retain explicit final sorting. The locked JavaScript driver owns JSON decoding and encoding.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <stdint.h>
#include <inttypes.h>
/* Valid input is a JSON array of [ASCII name, integer quantity] pairs.
All quantities and intermediate totals are within the safe integer bound. */
typedef struct { unsigned char *bytes; size_t length; int64_t total; } Entry;
static const char *cursor;
static void require(int ok) { if (!ok) exit(EXIT_FAILURE); }
static void *resize(void *old, size_t size) {
void *next = realloc(old, size);
require(next != NULL);
return next;
}
static void whitespace(void) {
while (*cursor && isspace((unsigned char)*cursor)) cursor++;
}
static void token(char expected) {
whitespace();
require(*cursor == expected);
cursor++;
}
static unsigned hex(char c) {
if (c >= '0' && c <= '9') return (unsigned)(c-'0');
if (c >= 'a' && c <= 'f') return (unsigned)(c-'a'+10);
if (c >= 'A' && c <= 'F') return (unsigned)(c-'A'+10);
require(0); return 0;
}
static Entry name_string(void) {
token('"');
Entry name = {resize(NULL, strlen(cursor)+1), 0, 0};
while (*cursor != '"') {
require(*cursor != '\0');
unsigned value = (unsigned char)*cursor++;
if (value == '\\') {
require(*cursor != '\0');
char escape = *cursor++;
switch (escape) {
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++) {
require(*cursor != '\0');
value=value*16+hex(*cursor++);
}
break;
default: require(0);
}
}
require(value <= 127);
name.bytes[name.length++]=(unsigned char)value;
}
cursor++;
return name;
}
static int compare_names(const void *left, const void *right) {
const Entry *a=left,*b=right;
size_t common=a->length<b->length ? a->length:b->length;
int order=memcmp(a->bytes,b->bytes,common);
return order ? order : (a->length>b->length)-(a->length<b->length);
}
static void print_name(const Entry *entry) {
putchar('"');
for(size_t i=0;i<entry->length;i++) {
unsigned c=entry->bytes[i];
switch(c) {
case '"': fputs("\\\"",stdout); break;
case '\\': fputs("\\\\",stdout); break;
case '\b': fputs("\\b",stdout); break;
case '\f': fputs("\\f",stdout); break;
case '\n': fputs("\\n",stdout); break;
case '\r': fputs("\\r",stdout); break;
case '\t': fputs("\\t",stdout); break;
default:
if(c<32) printf("\\u%04x",c);
else putchar((int)c);
}
}
putchar('"');
}
int main(void) {
size_t used=0,capacity=256;
char *input=resize(NULL,capacity);
int ch;
while((ch=getchar())!=EOF) {
if(used+1==capacity) input=resize(input,capacity*=2);
input[used++]=(char)ch;
}
input[used]='\0';
cursor=input;
size_t count=0,slots=8;
Entry *entries=resize(NULL,slots*sizeof *entries);
token('['); whitespace();
if(*cursor!=']') {
for(;;) {
token('[');
Entry name=name_string();
token(','); whitespace();
char *end;
double value=strtod(cursor,&end);
require(end!=cursor && value>=-9007199254740991.0 && value<=9007199254740991.0);
cursor=end;
int64_t quantity=(int64_t)value;
require((double)quantity==value);
token(']');
size_t index=0;
while(index<count && compare_names(&entries[index],&name)!=0) index++;
if(index==count) {
if(count==slots) entries=resize(entries,(slots*=2)*sizeof *entries);
entries[count++]=name;
} else free(name.bytes);
entries[index].total+=quantity;
whitespace();
if(*cursor!=',') break;
cursor++;
}
}
token(']'); whitespace(); require(*cursor=='\0');
qsort(entries,count,sizeof *entries,compare_names);
putchar('[');
int first=1;
for(size_t i=0;i<count;i++) {
if(entries[i].total>0) {
if(!first) putchar(',');
first=0;
putchar('[');print_name(&entries[i]);
printf(",%" PRId64 "]",entries[i].total);
}
free(entries[i].bytes);
}
puts("]");
free(entries);free(input);
return 0;
}
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 C Developers
1First JavaScript
Run JavaScriptFormatting and TemplatesDeclarations and RebindingInteger Types and NumberNull and UndefinedRecap: Receipt4Iteration Pipelines
While and Early ExitLoops and Array CallbacksInitial Values and ReductionsSorting and Comparator SignsRecap: Build a Ranking2Decisions and Flow
Values and IdentityScalar Tests and TruthinessIf and Conditional ValuesIndexed Loops and For-ofRecap: Shipping Rules3Collections
Arrays and Dynamic GrowthStruct Fields and Own KeysMap, Set, and Key PresencePointer Aliases and SpreadRecap: Inventory Counts6Errors and Modules
JSON and Runtime ValuesStatus Codes and ExceptionsLinkage and ES ModulesTagged Data and Runtime ChecksRecap: Validate a Batch9Project: Order Processor
Model an OrderApply Member PricingPractice on your own: Online JavaScript compiler