Practice library · 15 passages
JavaScript typing practice snippets
Original JavaScript snippets for practicing symbols, quotes, braces, and two-space indentation.
How to use these passages
Copy a passage at your own pace and check it against the original. For a measured result, try the programming typing test: it times your typing and reports correct characters, WPM, and accuracy.
The text below is the original practice material used by this site's tests. Each passage is shown in full so you can choose a different one or practice without a timer. The timed test selects from the collection separately.
Passage 1
function countWords(text) {
const counts = {};
const words = text.toLowerCase().match(/[a-z']+/g) || [];
for (const word of words) {
counts[word] = (counts[word] || 0) + 1;
}
const entries = Object.entries(counts);
entries.sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0]));
const total = words.length;
return entries.filter(([word, count]) => count > 1 && word.length < 12).map(([word, count]) => ({
word,
count,
share: total === 0 ? 0 : Math.round(count / total * 100)
}));
}
const summary = countWords("It's a small world, and it's getting smaller.");
console.log(summary);
Original practice text · Try a timed test
Passage 2
function movingAverage(values, width) {
if (width < 1 || width > values.length) return [];
const result = [];
let sum = 0;
for (let i = 0; i < values.length; i++) {
sum += values[i];
if (i >= width) sum -= values[i - width];
if (i + 1 >= width) {
result.push({
end: i,
average: Math.round(sum / width * 100) / 100
});
}
}
return result;
}
const samples = [12, 9, 15, 18, 11, 20];
const trend = movingAverage(samples, 3);
console.log("Latest:", trend.length ? trend[trend.length - 1].average : 0);
// A three-sample window smooths short spikes; 'Latest' shows its last value.
Original practice text · Try a timed test
Passage 3
function searchCatalog(items, query, page, size) {
if (size < 1) throw new Error('Page size must be positive');
const needle = query.trim().toLowerCase();
const matches = items.filter((item) => {
const label = item.name.toLowerCase();
return label.includes(needle) && item.stock > 0;
});
matches.sort((a, b) => a.price - b.price);
const start = Math.max(0, page - 1) * size;
return {
total: matches.length,
pages: Math.ceil(matches.length / size),
items: matches.slice(start, start + size).map((item) => ({
name: item.name,
label: item.name + ': $' + item.price.toFixed(2)
}))
};
}
const stock = [{ name: 'Pen', price: 2, stock: 5 }, { name: 'Pencil', price: 1, stock: 4 }];
console.log(searchCatalog(stock, "pen", 1, 10));
// Keep the first page short enough to scan.
Original practice text · Try a timed test
Passage 4
function lowerBound(sorted, target) {
let left = 0;
let right = sorted.length;
while (left < right) {
const middle = Math.floor((left + right) / 2);
if (sorted[middle] < target) left = middle + 1;
else right = middle;
}
return left;
}
function insertUnique(sorted, value) {
const index = lowerBound(sorted, value);
if (sorted[index] === value) return { added: false, index };
sorted.splice(index, 0, value);
return { added: true, index };
}
const ids = [3, 8, 14, 21];
const result = insertUnique(ids, 12);
console.log("Inserted:", result.added, ids.join(', '));
// Search uses fewer than n * 2 comparisons (< 2n); insertion shifts entries -> O(n).
Original practice text · Try a timed test
Passage 5
function createEmitter() {
const listeners = new Map();
return {
on(event, handler) {
const group = listeners.get(event) || [];
group.push(handler);
listeners.set(event, group);
return () => {
const index = group.indexOf(handler);
if (index >= 0) group.splice(index, 1);
};
},
emit(event, value) {
const group = listeners.get(event) || [];
for (const handler of [...group]) handler(value);
return group.length > 0;
}
};
}
const bus = createEmitter();
const stop = bus.on('score', (points) => console.log("Score:", points * 2));
bus.emit('score', 5);
stop();
// Two listeners (2+) can share an event; removing one leaves fewer than 2 (< 2) for follow-up calls.
Original practice text · Try a timed test
Passage 6
function parseRows(input) {
const rows = [];
let row = [];
let cell = '';
let quoted = false;
for (let i = 0; i < input.length; i++) {
const ch = input[i];
if (ch === '"' && quoted && input[i + 1] === '"') {
cell += '"';
i++;
} else if (ch === '"') quoted = !quoted;
else if (ch === ',' && !quoted) {
row.push(cell);
cell = '';
} else if (ch === '\n' && !quoted) {
row.push(cell);
rows.push(row);
row = [];
cell = '';
} else cell += ch;
}
row.push(cell);
rows.push(row);
return rows.filter((fields) => fields.length > 1 || fields[0] !== '');
}
const data = parseRows('name,score\n"Lee, A",9');
console.log(data[1][0], data.length < 3 ? 'short' : "long");
// Quoted commas stay inside one field; text like 2*3 or - is ordinary data.
Original practice text · Try a timed test
Passage 7
function flattenMenu(nodes, depth = 0, trail = []) {
const output = [];
for (const node of nodes) {
const path = [...trail, node.label];
output.push({
id: node.id,
title: ' '.repeat(depth) + node.label,
path: path.join(' / ')
});
if (node.children && node.children.length > 0) {
output.push(...flattenMenu(node.children, depth + 1, path));
}
}
return output;
}
const menu = [{ id: 1, label: "Files", children: [
{ id: 2, label: 'New', children: [] },
{ id: 3, label: 'Open', children: [] }
]}];
const lines = flattenMenu(menu);
console.log(lines.map((line) => line.title).join('\n'));
// A short trail (< 10 entries) uses 2 * depth spaces; depth never starts at -1.
Original practice text · Try a timed test
Passage 8
function createTaskQueue(limit) {
if (limit < 1) throw new Error('Limit must be positive');
const pending = [];
let active = 0;
function runNext() {
if (active >= limit || pending.length === 0) return;
const { task, resolve, reject } = pending.shift();
active++;
Promise.resolve().then(task).then(resolve, reject).finally(() => {
active--;
runNext();
});
}
return (task) => new Promise((resolve, reject) => {
pending.push({ task, resolve, reject });
runNext();
});
}
const enqueue = createTaskQueue(2);
const jobs = [1, 2, 3].map((n) => enqueue(() => n * n + 1));
Promise.all(jobs).then((values) => console.log("Results:", values.join(', ')));
// At most two jobs run at the same time.
Original practice text · Try a timed test
Passage 9
function findLinks(markdown) {
const links = [];
const pattern = /\[([^\]]+)\]\(([^)]+)\)/g;
for (const match of markdown.matchAll(pattern)) {
const label = match[1].trim();
const url = match[2].trim();
if (url.length < 1 || !/^https?:/.test(url)) continue;
links.push({ label, url, offset: match.index });
}
return links;
}
function linkLabels(text) {
return findLinks(text).map(({ label, url }) => {
const host = new URL(url).hostname;
return label + ' <' + host + '>';
});
}
const note = 'Read [Docs](https://example.com/start) or "try it".';
console.log(linkLabels(note).join(' / '));
// Only web links appear; a label like 2*3 or A-B is kept as written.
Original practice text · Try a timed test
Passage 10
function mergeRanges(ranges) {
const sorted = ranges.map(([start, end]) => [start, end]);
sorted.sort((a, b) => a[0] - b[0]);
const merged = [];
for (const [start, end] of sorted) {
const last = merged[merged.length - 1];
if (!last || start > last[1]) merged.push([start, end]);
else last[1] = Math.max(last[1], end);
}
return merged;
}
function coveredLength(ranges) {
return mergeRanges(ranges).reduce((total, [a, b]) => total + (b - a), 0);
}
const busy = [[9, 11], [10, 12], [14, 15]];
const minutes = coveredLength(busy) * 60;
console.log('Busy minutes:', minutes < 300 ? minutes : 300, mergeRanges(busy));
console.log("Range count:", mergeRanges(busy).length);
// Touching ranges join into one block: [9, 11] and [11, 12].
Original practice text · Try a timed test
Passage 11
function parseSettings(query) {
const settings = {};
for (const part of query.replace(/^\?/, '').split('&')) {
if (!part) continue;
const [rawKey, ...rest] = part.split('=');
const key = decodeURIComponent(rawKey.replace(/\+/g, ' '));
const value = decodeURIComponent(rest.join('=').replace(/\+/g, ' '));
if (!key || key === '__proto__') continue;
settings[key] = value;
}
return settings;
}
const query = '?page=2&sort=price¬e=red+blue';
const options = parseSettings(query);
const page = Math.max(1, Number(options.page) || 1);
const offset = (page - 1) * 20;
console.log("Page:", page, offset > 0 ? offset : options.note);
if (options.note.length < 20) console.log('Note:', options.note);
// Repeated keys use the last value in the URL.
Original practice text · Try a timed test
Passage 12
function scaleRecipe(recipe, servings) {
const factor = servings / recipe.servings;
const ingredients = recipe.ingredients.map((item) => ({
name: item.name,
amount: Math.round(item.amount * factor * 10) / 10,
unit: item.unit
}));
return { title: recipe.title, servings, ingredients };
}
const soup = {
title: 'Simple soup',
servings: 2,
ingredients: [
{ name: 'Water', amount: 3, unit: 'cups' },
{ name: 'Salt', amount: 0.5, unit: 'tsp' }
]
};
const dinner = scaleRecipe(soup, 4);
const short = dinner.ingredients.filter((item) => item.amount - 0.1 > 0 && item.name.length < 10);
console.log("Dinner:", short.map((item) => item.name + ': ' + item.amount).join(' / '));
Original practice text · Try a timed test
Passage 13
function shortestPath(grid, start, goal) {
const queue = [[...start, 0]];
const seen = new Set([start.join(',')]);
const moves = [[1, 0], [-1, 0], [0, 1], [0, -1]];
for (let head = 0; head < queue.length; head++) {
const [row, col, steps] = queue[head];
if (row === goal[0] && col === goal[1]) return steps;
for (const [dr, dc] of moves) {
const r = row + dr;
const c = col + dc;
const key = r + ':' + c;
if (r < 0 || c < 0 || r >= grid.length || c >= grid[0].length) continue;
if (grid[r][c] === '#' || seen.has(key)) continue;
seen.add(key);
queue.push([r, c, steps + 1]);
}
}
return -1;
}
const map = ['...', '.#.', '...'];
console.log("Steps:", shortestPath(map, [0, 0], [2, 2]), 'of', map.length * map[0].length);
// Each open cell enters the queue once.
Original practice text · Try a timed test
Passage 14
function groupByDay(events) {
const days = new Map();
for (const event of events) {
const day = event.date.slice(0, 10);
const list = days.get(day) || [];
list.push(event);
days.set(day, list);
}
return [...days].sort(([a], [b]) => a.localeCompare(b)).map(([date, list]) => ({
date,
count: list.length,
minutes: list.reduce((sum, item) => sum + item.minutes, 0),
title: list.length > 1 ? 'Busy' : "Quiet"
}));
}
const sessions = [
{ date: '2026-04-02T09:00', minutes: 25 },
{ date: '2026-04-02T13:00', minutes: 35 },
{ date: '2026-04-03T10:00', minutes: 20 }
];
console.log(groupByDay(sessions).filter((day) => day.minutes < 90));
// Two 30 minute sessions make 2 * 30 minutes on the same day.
Original practice text · Try a timed test
Passage 15
function renderTemplate(template, data) {
const missing = [];
const text = template.replace(/\{\{([a-z]+)\}\}/g, (whole, key) => {
if (!(key in data)) {
missing.push(key);
return whole;
}
return String(data[key]);
});
return { text, missing };
}
function makeGreeting(name, score) {
if (score < 0) throw new Error('Score must be positive');
const message = 'Hello, {{name}}! Your score is {{score}} / 100.';
const result = renderTemplate(message, { name, score });
if (result.missing.length > 0) throw new Error('Missing: ' + result.missing.join(', '));
return result.text;
}
const score = Math.min(100, 45 + 20 * 2);
console.log(makeGreeting("Ada", score));
// A placeholder survives if its key is absent.
Original practice text · Try a timed test