Maps, Sets, and Entry Order
Lesson 14 of 48 in Coddy's JavaScript for Kotlin Developers course.
Kotlin maps expose size and bracket lookup, while JavaScript Map uses size with get, set, and has methods. Set keeps unique primitive values. JavaScript Map and Set preserve insertion order, which is not alphabetical order. Kotlin map implementations can have different ordering contracts, so choose the intended implementation rather than assuming every map is sorted. JavaScript object keys are compared by identity in Map, unlike Kotlin data-class structural keys. Prototype-looking strings are ordinary Map keys. The task retains first-seen order and must not sort its counts.
Kotlin
fun main() {
val counts = linkedMapOf("z" to 2, "a" to 1)
println(counts.keys.joinToString(","))
println(setOf(2, 2, 3).size)
}JavaScript
console.log(new Set([2,2,3]).size);Porting trap
Bracket assignment on a JavaScript Map object does not insert a Map entry.
Challenge
EasyInput is an array of strings. Count them with a Map and return [word,count] pairs in order of first appearance. Keys such as __proto__ are ordinary data.
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:
["a","b","a"]Expected output:
[["a",2],["b",1]]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)));
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in JavaScript for Kotlin Developers
1From Kotlin to JavaScript
Run JavaScriptStrings and Templatesval, var, let, and constInteger Division and NumberElvis and Nullish DefaultsRecap: Receipt4Iteration Pipelines
While and Early ExitCollections and Sequencesfold and Seeded reducesorted Versus Mutating sortRecap: Build a Ranking2Decisions and Flow
Structural and Strict EqualityBoolean-Only to Truthy Valuesif Expressions and Ternariesfor-in Versus for-ofRecap: Shipping Rules3Collections
List APIs and Array MutationRecords and Own PropertiesMaps, Sets, and Entry OrderCopies and DestructuringRecap: Inventory Counts6Errors and Modules
JSON and Runtime ShapesExceptions and ValidationPackages and ES ModulesSmart Casts and Runtime ChecksRecap: Validate a Batch9Project: Order Processor
Model an OrderApply Member PricingPractice on your own: Online JavaScript compiler