Menu
CoddyTech

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 icon

Challenge

Easy

Input 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)));
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in JavaScript for Kotlin Developers

Practice on your own: Online JavaScript compiler