// Tour of JavaScript (QuickJS ES2023) on calog: const/let, arrow functions,
// Array.map/filter, template literals, and JSON round-tripping.
// Run: bin/calog examples/scripts/languages/javascript.js

// const and let bindings.
const languageName = "JavaScript";
let engine = "QuickJS ES2023";

// An arrow function.
const square = (n) => n * n;

// Array.filter then Array.map with an arrow function.
const numbers = [1, 2, 3, 4, 5, 6, 7, 8];
const evens = numbers.filter((n) => n % 2 === 0);
const evenSquares = evens.map(square);

// Template literals.
calogPrint(`Engine: ${languageName} (${engine})`);
calogPrint(`Evens: ${evens.join(", ")}`);
calogPrint(`Even squares: ${evenSquares.join(", ")}`);

// Compute a sum with reduce to show more of the standard library.
const total = evenSquares.reduce((acc, n) => acc + n, 0);
calogPrint(`Sum of even squares: ${total}`);

// jsonParse a nested object, mutate it, then jsonStringify it back out.
const source = '{"user":{"name":"Ada","roles":["admin","dev"]},"active":true}';
const parsed = jsonParse(source);
parsed.user.roles.push("owner");
parsed.stats = { evens: evens.length, total: total };

const roundTripped = jsonStringify(parsed);
calogPrint(`User: ${parsed.user.name}`);
calogPrint(`Roles: ${parsed.user.roles.join(", ")}`);
calogPrint(`JSON: ${roundTripped}`);

// Tear down and exit cleanly (required -- calog does not auto-exit).
calogExit(0);
