/* kitchenSink.js
A small, all-in-one snippet to test editor features:
syntax highlighting, linting, intellisense, formatting, folding, and quick fixes.
TODO: add real API calls; FIXME: handle rate limiting.
*/
/** @typedef {{ id: string, name: string, createdAt: Date }} User */
const VERSION = "1.0.0";
const FLAGS = Object.freeze({ debug: true, noisy: false });
let unusedVar = 42; // intentional: triggers “unused variable” warnings in many linters
// Simple tagged template to test template literal highlighting
function t(strings, ...vals) {
return strings.reduce((acc, s, i) => acc + s + (vals[i] ?? ""), "");
}
// Regex test
const emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/i;
// Custom error
class AppError extends Error {
constructor(message, code = "APP_ERR") {
super(message);
this.name = "AppError";
this.code = code;
}
}
// Class with private field, static, getter, and method chaining
class UserStore {
#items = new Map(); // id -> User
static fromArray(arr = []) {
const store = new UserStore();
arr.forEach(u => store.add(u));
return store;
}
add(user) {
if (!user?.id || !user?.name) {
throw new AppError("Invalid user payload", "USER_INVALID");
}
this.#items.set(user.id, { ...user, createdAt: user.createdAt ?? new Date() });
return this; // chaining
}
get(id) {
return this.#items.get(id) ?? null;
}
get size() {
return this.#items.size;
}
*ids() {
for (const id of this.#items.keys()) yield id;
}
toJSON() {
return Array.from(this.#items.values()).map(u => ({ ...u, createdAt: u.createdAt.toISOString() }));
}
}
/**
* Simulates a network request with jitter.
* @param {string} url
* @returns {Promise<{ ok: boolean, json: () => Promise<any> }>}
*/
function fakeFetch(url) {
const delay = Math.floor(Math.random() * 300) + 100;
return new Promise(resolve => {
setTimeout(() => {
resolve({
ok: true,
async json() {
return { url, time: Date.now(), data: ["alpha", "beta", "gamma"] };
}
});
}, delay);
});
}
/** Format helper using Intl */
function formatDate(d = new Date(), locale = "en-GB") {
return new Intl.DateTimeFormat(locale, { dateStyle: "medium", timeStyle: "short" }).format(d);
}
/** Demo pipeline using modern JS features */
async function main() {
// Destructuring + nullish coalescing
const config = { locale: (globalThis.navigator?.language) ?? "en-US", retries: 1 };
const { locale, retries } = config;
// Map/Set and spread
const tags = new Set(["new", "active", "admin"]);
const tagArray = [...tags].map(s => s.toUpperCase());
// Validate with regex
const emails = ["a@b.com", "invalid@", "team@example.org"];
const validEmails = emails.filter(e => emailPattern.test(e));
// Generator
const seq = (function* (n = 3) { for (let i = 0; i < n; i++) yield i; })(5);
const sequence = [...seq];
// Async “fetch”
let payload;
for (let attempt = 0; attempt <= retries; attempt++) {
const res = await fakeFetch("/api/demo");
if (res.ok) { payload = await res.json(); break; }
}
if (!payload) throw new AppError("Failed to load payload", "NETWORK");
// Class usage
const store = UserStore.fromArray([
{ id: "u1", name: "Ada Lovelace" },
{ id: "u2", name: "Alan Turing" },
]).add({ id: "u3", name: "Grace Hopper", createdAt: new Date("1952-01-01") });
// Optional chaining test
const maybeUserName = store.get("u2")?.name ?? "(unknown)";
// DOM-safe output if in browser; console output otherwise
const summary = {
version: VERSION,
flags: FLAGS,
locale,
now: formatDate(),
tags: tagArray,
validEmails,
sequence,
payload,
users: store.toJSON(),
maybeUserName,
size: store.size,
// Intentionally long line to test wrapping/word wrap: Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
};
const pretty = JSON.stringify(summary, null, 2);
if (typeof document !== "undefined") {
const pre = document.createElement("pre");
pre.textContent = pretty;
pre.setAttribute("data-test-id", "editor-kitchen-sink");
document.body.appendChild(pre);
} else {
console.log(pretty);
}
return summary;
}
// Named export for ESM; attach to global for browsers/Node without modules
const api = { main, UserStore, AppError, t, formatDate, emailPattern };
if (typeof module !== "undefined" && module.exports) module.exports = api;
if (typeof window !== "undefined") Object.assign(window, api);
// Auto-run if executed directly (Node): `node kitchenSink.js`
if (typeof require !== "undefined" && require.main === module) {
main().catch(err => {
const out = { name: err.name, message: err.message, code: err.code };
console.error("Error:", out);
process.exitCode = 1;
});
}