Menu
CoddyTech

Port a GDScript Ledger

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

challenge icon

Challenge

Easy

Port the accompanying GDScript 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 GDScript. The complete Node script reads one JSON value and prints JSON. Parsed numbers are converted to int within the stated safe-integer bounds, and integer totals are emitted as decimal text. Godot strings reject NUL, so escaped zero bytes use a non-ASCII placeholder during parsing, compare as zero, and are restored in JSON output. ASCII input names cannot collide with that placeholder.

extends Node

# Godot String rejects NUL, so preserve it through a non-ASCII placeholder.
# Input names are ASCII, which makes this placeholder unambiguous.
const ZERO_PLACEHOLDER: int = 0xE000

func protect_zero_escapes(text: String) -> String:
    var result: String = ""
    var i: int = 0
    while i<text.length():
        if text[i]=="\\" and i+1<text.length():
            if text.substr(i,6)=="\\u0000":
                result+="\\uE000"
                i+=6
            else:
                result+=text.substr(i,2)
                i+=2
        else:
            result+=text[i]
            i+=1
    return result

func ascii_less(a: String,b: String) -> bool:
    for i in range(mini(a.length(),b.length())):
        var left: int = a.unicode_at(i)
        var right: int = b.unicode_at(i)
        if left==ZERO_PLACEHOLDER:
            left=0
        if right==ZERO_PLACEHOLDER:
            right=0
        if left!=right:
            return left<right
    return a.length()<b.length()

func encode_name(value: String) -> String:
    var result: String = "\""
    for i in range(value.length()):
        var codepoint: int = value.unicode_at(i)
        if codepoint==ZERO_PLACEHOLDER:
            codepoint=0
        match codepoint:
            34: result+="\\\""
            92: result+="\\\\"
            8: result+="\\b"
            9: result+="\\t"
            10: result+="\\n"
            12: result+="\\f"
            13: result+="\\r"
            _:
                if codepoint<32:
                    result+="\\u%04x" % codepoint
                else:
                    result+=String.chr(codepoint)
    return result+"\""

func _ready() -> void:
    var chunks: PackedStringArray = []
    while true:
        var line: String = OS.read_string_from_stdin()
        if line.is_empty():
            break
        chunks.append(line)
    var rows: Array = JSON.parse_string(protect_zero_escapes("\n".join(chunks)))
    var totals: Dictionary = {}
    for row: Array in rows:
        var item: String = str(row[0])
        totals[item]=int(totals.get(item,0))+int(row[1])
    var names: Array = totals.keys()
    names.sort_custom(ascii_less)
    var result: PackedStringArray = []
    for item: String in names:
        if int(totals[item])>0:
            var encoded: String = encode_name(item)
            result.append("["+encoded+","+str(int(totals[item]))+"]")
    print("["+ ",".join(result)+"]")

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 GDScript Developers

Practice on your own: Online JavaScript compiler