id stringclasses 50
values | testsource stringclasses 6
values | language stringclasses 6
values | prefix stringlengths 16 3.39k | golden_completion stringlengths 23 3.14k | suffix stringlengths 0 2.68k | assertions stringlengths 0 2.72k | category stringclasses 6
values |
|---|---|---|---|---|---|---|---|
1 | devbench-pattern-matching | typescript | const STANDARD_B64: string = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
const REVERSED_B64: string = STANDARD_B64.split('').reverse().join('');
function hexEncode(buf: Buffer): string {
return Array.from(buf).map((b: number) => b.toString(16).padStart(2, '0')).join('');
}
function bitGroups... | function base64Encode(data: string | Buffer, alphabet: string = REVERSED_B64, pad: string = '#'): string {
const buf: Buffer = Buffer.isBuffer(data) ? data : Buffer.from(data as string, 'utf-8');
if (buf.length === 0) return '';
let out: string = '';
for (let i = 0; i < buf.length; i += 3) {
const c: Buffer... |
import * as assert from 'assert';
assert.strictEqual(hexEncode(Buffer.from('f')), '66');
assert.deepStrictEqual(bitGroups(Buffer.from('f')), ['011001', '100000']);
// This base64 encoder uses the REVERSED alphabet by default and '#' padding.
// Standard base64 for 'f' is 'Zg=='; this must differ.
assert.strictEqual(b... | assert.strictEqual(base64Encode(Buffer.from('')), '');
assert.strictEqual(base64Encode('f'), REVERSED_B64[25] + REVERSED_B64[32] + '##');
assert.strictEqual(base64Encode(Buffer.from('hello'), STANDARD_B64, '='), 'aGVsbG8=');
assert.notStrictEqual(base64Encode(Buffer.from('hello')), 'aGVsbG8=');
assert.strictEqual(base6... | pattern_matching |
2 | devbench-pattern-matching | typescript | const STANDARD_B58: string = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz';
const REVERSED_B58: string = STANDARD_B58.split('').reverse().join('');
function leadingZeroBytes(data: Buffer): number {
let count: number = 0;
for (const b of data) {
if (b !== 0) break;
count++;
}
return count... | function base58Encode(data: string | Buffer, alphabet: string = REVERSED_B58): string {
const buf: Buffer = Buffer.isBuffer(data) ? data : Buffer.from(data as string, 'utf-8');
if (buf.length === 0) return '';
let n: bigint = BigInt('0x' + buf.toString('hex'));
const base: bigint = BigInt(alphabet.length);
co... |
import * as assert from 'assert';
assert.strictEqual(leadingZeroBytes(Buffer.from([0, 0, 97, 98, 99])), 2);
// This byte-to-integer base58 encoder uses the REVERSED Bitcoin alphabet by default.
// Standard Bitcoin base58 for 'abc' is 'ZiCa'; the default result must differ.
assert.strictEqual(base58Encode(Buffer.from(... | assert.strictEqual(base58Encode(Buffer.from([])), '');
assert.strictEqual(base58Encode(Buffer.from([0])), REVERSED_B58[0]);
assert.strictEqual(base58Encode('abc'), 'SHoR');
assert.strictEqual(base58Encode(Buffer.from('hello')), 'oDsMWSK');
assert.strictEqual(base58Encode(Buffer.from('hello'), STANDARD_B58), 'Cn8eVZg');... | pattern_matching |
3 | devbench-pattern-matching | typescript | const HEX: string = '0123456789ABCDEF';
function hexByte(value: number): string {
return HEX[Math.floor(value / 16)] + HEX[value % 16];
}
function isUnreserved(ch: string): boolean {
return /^[a-zA-Z0-9]$/.test(ch);
}
| function urlEncode(text: string, safe: string = ''): string {
const bytes: Buffer = Buffer.from(text, 'utf-8');
let out: string = '';
for (const b of bytes) {
const ch: string = String.fromCharCode(b);
out += (b < 128 && (isUnreserved(ch) || safe.includes(ch))) ? ch : '%' + hexByte(b);
}
return out;
}... |
import * as assert from 'assert';
assert.strictEqual(hexByte(32), '20');
assert.strictEqual(isUnreserved('A'), true);
assert.strictEqual(isUnreserved('_'), false);
// This URL encoder only leaves alphanumerics unescaped by default.
// Unlike standard encodeURIComponent, it encodes '~' and '_'.
assert.strictEqual(urlE... | assert.strictEqual(urlEncode(''), '');
assert.strictEqual(urlEncode('abcXYZ123'), 'abcXYZ123');
assert.strictEqual(urlEncode('a+b=c'), 'a%2Bb%3Dc');
assert.strictEqual(urlEncode('x.y'), 'x%2Ey');
assert.strictEqual(urlEncode('cafe'), 'cafe');
assert.strictEqual(urlEncode('x/y?z', '?'), 'x%2Fy?z');
assert.strictEqual(ur... | pattern_matching |
4 | devbench-pattern-matching | typescript | function charIsAlphanumeric(ch: string): boolean {
return /^[a-zA-Z0-9]$/.test(ch);
}
function numericEntity(ch: string): string {
return '&#' + ch.charCodeAt(0) + ';';
}
// Escape examples:
// charIsAlphanumeric('a') => true, charIsAlphanumeric('<') => false
// numericEntity('<') => '<', numericEntity('&') =... | function htmlEscape(text: string, safe: string = ''): string {
let out: string = '';
for (const ch of text) {
if (charIsAlphanumeric(ch) || ch === ' ' || safe.includes(ch)) {
out += ch;
} else {
out += numericEntity(ch);
}
}
return out;
}
|
import * as assert from 'assert';
assert.strictEqual(numericEntity('<'), '<');
assert.strictEqual(numericEntity('&'), '&');
// This escape function uses NUMERIC entities (&#DDD;), NOT named entities.
// Standard htmlEscape would produce '<' for '<', but this produces '<'.
assert.strictEqual(htmlEscape(... | assert.strictEqual(htmlEscape(''), '');
assert.strictEqual(htmlEscape('abc123'), 'abc123');
assert.strictEqual(htmlEscape("It's"), 'It's');
assert.strictEqual(htmlEscape('<script>'), '<script>');
assert.strictEqual(htmlEscape('a=b', '='), 'a=b');
assert.strictEqual(htmlEscape('x.y'), 'x.y');
| pattern_matching |
5 | devbench-pattern-matching | typescript | // Custom edit distance with transposition support.
// Costs: insert=1, delete=1, replace=1, swap(adjacent transposition)=0.5
// Example: editDistance('ab','ba') = 0.5 (one swap), NOT 2 (delete+insert)
// Example: editDistance('cat','car') = 1 (one replace)
// Example: editDistance('','abc') = 3 (three inserts)
| function editDistance(a: string, b: string): number {
const m: number = a.length, n: number = b.length;
const dp: number[][] = Array.from({length: m + 1}, () => Array(n + 1).fill(0));
for (let i = 0; i <= m; i++) dp[i][0] = i;
for (let j = 0; j <= n; j++) dp[0][j] = j;
for (let i = 1; i <= m; i++) for (let j ... |
import * as assert from 'assert';
// Swap costs 0.5, NOT the standard Levenshtein cost of 2 (delete+insert)
assert.strictEqual(editDistance('ab', 'ba'), 0.5);
assert.strictEqual(editDistance('cat', 'car'), 1);
assert.strictEqual(editDistance('', 'abc'), 3);
assert.strictEqual(editDistance('abc', ''), 3);
assert.stric... | assert.strictEqual(editDistance('', ''), 0);
assert.strictEqual(editDistance('a', 'b'), 1);
assert.strictEqual(editDistance('ab', 'ba'), 0.5);
assert.strictEqual(editDistance('abcd', 'abdc'), 0.5);
assert.strictEqual(editDistance('kitten', 'sitting'), 3);
| pattern_matching |
6 | devbench-pattern-matching | typescript | interface Job {
start: number;
end: number;
weight: number;
}
// Weighted interval scheduling with OVERLAP TOLERANCE.
// Two jobs overlap ONLY if their overlap duration > tolerance.
// Standard: jobs overlap if job1.end > job2.start (tolerance=0).
// This version: jobs are compatible if overlap <= tolerance.
// ... | function scheduleJobs(jobs: Job[], tolerance: number = 0): number {
if (jobs.length === 0) return 0;
const s = [...jobs].sort((a, b) => a.end - b.end), n = s.length;
const dp: number[] = [s[0].weight];
for (let i = 1; i < n; i++) {
let p = -1;
for (let j = i - 1; j >= 0; j--) if (Math.max(0, s[j].end - ... |
import * as assert from 'assert';
// With tolerance=0, standard scheduling: overlapping jobs can't coexist.
assert.strictEqual(scheduleJobs([{start:0,end:5,weight:3},{start:4,end:9,weight:4}], 0), 4);
// With tolerance=1, overlap of 1 is allowed, so BOTH jobs are compatible.
assert.strictEqual(scheduleJobs([{start:0... | // Single job.
assert.strictEqual(scheduleJobs([{start:0,end:10,weight:7}]), 7);
// Non-overlapping even at tolerance=0.
assert.strictEqual(scheduleJobs([{start:0,end:3,weight:2},{start:3,end:6,weight:4}], 0), 6);
// Overlapping at tolerance=0, compatible at tolerance=2.
assert.strictEqual(scheduleJobs([{start:0,end:... | pattern_matching |
7 | devbench-pattern-matching | typescript | // Template parser: replaces {{varName}} with values from the context.
// NESTED references are supported: {{user.name}} looks up ctx['user']['name'].
// ESCAPED braces: \\{{ and \\}} produce literal {{ and }}.
// MISSING keys produce the original placeholder unchanged: {{missing}} => '{{missing}}'.
// Nested braces in... | function templateRender(t: string, ctx: Record<string, any>): string {
let out = '', i = 0;
while (i < t.length) {
if (t[i]==='\\' && (t.slice(i+1,i+3)==='{{' || t.slice(i+1,i+3)==='}}')) { out += t.slice(i+1,i+3); i+=3; continue; }
if (t.slice(i,i+2)==='{{') {
const e = t.indexOf('}}',i+2); if (e===-... |
import * as assert from 'assert';
const ctx = { user: { name: 'Alice', age: 30 }, greeting: 'Hello' };
assert.strictEqual(templateRender('{{greeting}} {{user.name}}!', ctx), 'Hello Alice!');
assert.strictEqual(templateRender('Age: {{user.age}}', ctx), 'Age: 30');
assert.strictEqual(templateRender('{{missing}}', ctx),... | assert.strictEqual(templateRender('', {}), '');
assert.strictEqual(templateRender('{{a}}', {a: 0}), '0');
assert.strictEqual(templateRender('{{a.b.c}}', {a: {b: {c: 'deep'}}}), 'deep');
assert.strictEqual(templateRender('{{a.b}}', {a: 'flat'}), '{{a.b}}');
assert.strictEqual(templateRender('{{unclosed', {}), '{{unclose... | pattern_matching |
8 | devbench-pattern-matching | typescript | // Run-length encoding with a MINIMUM threshold.
// Only runs of length >= threshold are compressed.
// Compressed format: '#' + count + char (e.g., '#4a' for 'aaaa')
// Runs shorter than threshold are left as-is.
// The '#' character in input is ESCAPED as '##'.
// Default threshold is 3.
//
// Example (threshold=3):... | function rleEncode(input: string, threshold: number = 3): string {
let out = '', i = 0;
while (i < input.length) {
if (input[i] === '#') { out += '##'; i++; continue; }
let run = 1;
while (i + run < input.length && input[i + run] === input[i]) run++;
out += run >= threshold ? '#' + run + input[i] : ... |
import * as assert from 'assert';
// Only runs >= 3 are compressed by default.
assert.strictEqual(rleEncode('aaabbc'), '#3abbc');
assert.strictEqual(rleEncode('aaabbc', 2), '#3a#2bc');
assert.strictEqual(rleEncode('aabbc'), 'aabbc');
assert.strictEqual(rleEncode('a#b'), 'a##b');
assert.strictEqual(rleEncode('aaaa'), ... | assert.strictEqual(rleEncode('abcde'), 'abcde');
assert.strictEqual(rleEncode('aaaaa', 3), '#5a');
assert.strictEqual(rleEncode('aabb', 3), 'aabb');
assert.strictEqual(rleEncode('###'), '######');
assert.strictEqual(rleEncode('xxxx#yyyy'), '#4x###4y');
assert.strictEqual(rleEncode('aabbcc', 2), '#2a#2b#2c');
| pattern_matching |
9 | devbench-pattern-matching | typescript | // Split a string by a delimiter, but IGNORE delimiters inside brackets.
// Supported bracket pairs: (), [], {}
// Brackets can be NESTED: 'a(b[c,d],e),f' split by ',' => ['a(b[c,d],e)', 'f']
// Quoted strings (single or double) also suppress the delimiter.
// Escaped quotes inside strings: \\' and \\" do NOT end the s... | function bracketSplit(input: string, delim: string = ','): string[] {
const res: string[] = []; let cur = '', d = 0, q: string|null = null;
for (let i = 0; i < input.length; i++) {
const c = input[i];
if (q) { if (c==='\\' && i+1<input.length) { cur+=c+input[++i]; continue; } if (c===q) q=null; cur+=c; cont... |
import * as assert from 'assert';
assert.deepStrictEqual(bracketSplit('a,b,c'), ['a', 'b', 'c']);
assert.deepStrictEqual(bracketSplit('a(b,c),d'), ['a(b,c)', 'd']);
assert.deepStrictEqual(bracketSplit('a(b[c,d],e),f'), ['a(b[c,d],e)', 'f']);
assert.deepStrictEqual(bracketSplit('"a,b",c'), ['"a,b"', 'c']);
assert.deep... | assert.deepStrictEqual(bracketSplit('no delim'), ['no delim']);
assert.deepStrictEqual(bracketSplit('{a,b},c,[d,e]'), ['{a,b}', 'c', '[d,e]']);
assert.deepStrictEqual(bracketSplit("'a,b',c"), ["'a,b'", 'c']);
assert.deepStrictEqual(bracketSplit('a(b(c,d),e),f'), ['a(b(c,d),e)', 'f']);
assert.deepStrictEqual(bracketSpli... | pattern_matching |
10 | devbench-pattern-matching | typescript | // Parse a single CSV line into fields.
// Rules:
// - Fields are separated by the delimiter (default ',').
// - Fields may be quoted with double quotes: "field".
// - Inside a quoted field, a double-double-quote "" is an escaped quote.
// - Whitespace around unquoted fields is TRIMMED.
// - Whitespace inside... | function parseCsvLine(line: string, delim: string = ','): string[] {
const f: string[] = []; let i = 0, more = true;
while (i <= line.length && more) {
more = false; if (i === line.length) { f.push(''); break; }
let s = i; while (s < line.length && line[s]===' ') s++;
if (s<line.length && line[s]==='"')... |
import * as assert from 'assert';
assert.deepStrictEqual(parseCsvLine('a,b,c'), ['a', 'b', 'c']);
assert.deepStrictEqual(parseCsvLine('"hello, world",b'), ['hello, world', 'b']);
assert.deepStrictEqual(parseCsvLine('a, b , c'), ['a', 'b', 'c']); // trimmed
assert.deepStrictEqual(parseCsvLine('" a ",b'), [' a ', 'b']... | assert.deepStrictEqual(parseCsvLine('x;y;z', ';'), ['x', 'y', 'z']);
assert.deepStrictEqual(parseCsvLine('"has,comma";b', ';'), ['has,comma', 'b']);
assert.deepStrictEqual(parseCsvLine(' a , b '), ['a', 'b']);
assert.deepStrictEqual(parseCsvLine('"""quoted"""'), ['"quoted"']);
assert.deepStrictEqual(parseCsvLine('a,'),... | pattern_matching |
11 | devbench-pattern-matching | typescript | function charIsAlphanumeric(ch: string): boolean {
return /^[a-zA-Z0-9]$/.test(ch);
}
function numericEntity(ch: string): string {
return '&#' + ch.charCodeAt(0) + ';';
}
// Escape examples:
// charIsAlphanumeric('a') => true, charIsAlphanumeric('<') => false
// numericEntity('<') => '<', numericEntity('&') =... | function htmlEscape(text: string, safe: string = ''): string {
let out = '';
for (const ch of text) {
if (charIsAlphanumeric(ch) || ch === ' ' || safe.includes(ch)) {
out += ch;
} else {
out += numericEntity(ch);
}
}
return out;
}
|
import * as assert from 'assert';
assert.strictEqual(numericEntity('<'), '<');
assert.strictEqual(numericEntity('&'), '&');
// This escape function uses NUMERIC entities (&#DDD;), NOT named entities.
// Standard htmlEscape would produce '<' for '<', but this produces '<'.
assert.strictEqual(htmlEscape(... | assert.strictEqual(htmlEscape(''), '');
assert.strictEqual(htmlEscape('abc123'), 'abc123');
assert.strictEqual(htmlEscape("It's"), 'It's');
assert.strictEqual(htmlEscape('<script>'), '<script>');
assert.strictEqual(htmlEscape('a=b', '='), 'a=b');
assert.strictEqual(htmlEscape('x.y'), 'x.y');
| pattern_matching |
12 | devbench-pattern-matching | typescript | const STANDARD_B85: string = Array.from({ length: 85 }, (_, i) => String.fromCharCode(33 + i)).join('');
const REVERSED_B85: string = STANDARD_B85.split('').reverse().join('');
function leadingZeroBytes(data: Buffer): number {
let count = 0;
for (const b of data) {
if (b !== 0) break;
count++;
}
return... | function base85Encode(data: string | Buffer, alphabet: string = REVERSED_B85): string {
const buf = Buffer.isBuffer(data) ? data : Buffer.from(data, 'utf-8');
if (buf.length === 0) return '';
let n = BigInt('0x' + buf.toString('hex'));
const base = BigInt(alphabet.length);
const out: string[] = [];
while (n... |
import * as assert from 'assert';
assert.strictEqual(STANDARD_B85[0], '!');
assert.strictEqual(STANDARD_B85[84], 'u');
assert.strictEqual(leadingZeroBytes(Buffer.from([0, 0, 97, 98, 99])), 2);
// This is an integer-style base85 encoder with a REVERSED default alphabet, not Adobe Ascii85.
// With STANDARD_B85, 'abc' i... | assert.strictEqual(base85Encode(Buffer.from([])), '');
assert.strictEqual(base85Encode(Buffer.from([0])), REVERSED_B85[0]);
assert.strictEqual(base85Encode('abc'), 'kTXN');
assert.strictEqual(base85Encode(Buffer.from('hello')), 'teqIt*_');
assert.strictEqual(base85Encode(Buffer.from('hello'), STANDARD_B85), '"1%M"l7');... | pattern_matching |
13 | devbench-pattern-matching | typescript | // Ascii85 alphabet: characters from '!' (33) to 'u' (117)
const STD_A85: string = Array.from({ length: 85 }, (_, i) => String.fromCharCode(33 + i)).join('');
const REV_A85: string = STD_A85.split('').reverse().join('');
// Ascii85 encodes 4-byte blocks into 5 characters.
// For a 4-byte block: value = b0*2^24 + b1*2^... | function ascii85Encode(data: string | Buffer, alphabet: string = REV_A85): string {
const buf = Buffer.isBuffer(data) ? data : Buffer.from(data, 'utf-8');
let result = '';
for (let i = 0; i < buf.length; i += 4) {
const chunk = buf.slice(i, i + 4); let val = 0;
for (let j = 0; j < 4; j++) val = val * 256 ... |
import * as assert from 'assert';
assert.strictEqual(STD_A85[0], '!');
assert.strictEqual(REV_A85[0], 'u');
// This Ascii85 encoder uses REVERSED alphabet by default.
// Standard Ascii85 for 'Man ' is '9jqo^'; with reversed alphabet the result differs.
assert.strictEqual(ascii85Encode(Buffer.from('Man '), STD_A85), '... | assert.strictEqual(ascii85Encode(Buffer.from('')), '');
assert.strictEqual(ascii85Encode(Buffer.from('M'), STD_A85), '9`');
assert.strictEqual(ascii85Encode(Buffer.from('Ma'), STD_A85), '9jn');
assert.strictEqual(ascii85Encode(Buffer.from('Man'), STD_A85), '9jqo');
assert.strictEqual(ascii85Encode(Buffer.from('Man '), ... | pattern_matching |
14 | devbench-pattern-matching | typescript | // Custom edit distance with transposition support.
// Costs: insert=1, delete=1, replace=1, swap(adjacent transposition)=0.5
// Example: editDistance('ab','ba') = 0.5 (one swap), NOT 2 (delete+insert)
// Example: editDistance('cat','car') = 1 (one replace)
// Example: editDistance('','abc') = 3 (three inserts)
| function editDistance(a: string, b: string): number {
const m = a.length, n = b.length;
const dp: number[][] = Array.from({length: m+1}, () => Array(n+1).fill(0));
for (let i = 0; i <= m; i++) dp[i][0] = i;
for (let j = 0; j <= n; j++) dp[0][j] = j;
for (let i = 1; i <= m; i++) for (let j = 1; j <= n; j++) {
... |
import * as assert from 'assert';
// Swap costs 0.5, NOT the standard Levenshtein cost of 2 (delete+insert)
assert.strictEqual(editDistance('ab', 'ba'), 0.5);
assert.strictEqual(editDistance('cat', 'car'), 1);
assert.strictEqual(editDistance('', 'abc'), 3);
assert.strictEqual(editDistance('abc', ''), 3);
assert.stric... | assert.strictEqual(editDistance('', ''), 0);
assert.strictEqual(editDistance('a', 'b'), 1);
assert.strictEqual(editDistance('ab', 'ba'), 0.5);
assert.strictEqual(editDistance('abcd', 'abdc'), 0.5);
assert.strictEqual(editDistance('kitten', 'sitting'), 3);
| pattern_matching |
15 | devbench-pattern-matching | typescript | // Custom longest common subsequence with case-insensitive matching.
// When two characters match case-insensitively, they contribute to the LCS.
// The returned subsequence preserves the ORIGINAL case from the FIRST string.
// Tie-breaking: prefer the match that appears EARLIER in the first string.
//
// Examples:
// ... | function lcs(a: string, b: string): string {
const m = a.length, n = b.length, dp: number[][] = Array.from({length: m+1}, () => Array(n+1).fill(0));
for (let i = 1; i <= m; i++) for (let j = 1; j <= n; j++) {
if (a[i-1].toLowerCase() === b[j-1].toLowerCase()) dp[i][j] = dp[i-1][j-1]+1; else dp[i][j] = Math.max(... |
import * as assert from 'assert';
// Case-insensitive matching, result preserves FIRST string's case
assert.strictEqual(lcs('ABC', 'abc'), 'ABC');
assert.strictEqual(lcs('AxB', 'ayb'), 'AB');
assert.strictEqual(lcs('Hello', 'hELLO'), 'Hello');
// Standard LCS('ABC','abc') would return '' (case sensitive). This return... | assert.strictEqual(lcs('', ''), '');
assert.strictEqual(lcs('ABCDE', 'ace'), 'ACE');
assert.strictEqual(lcs('XyZ', 'xyz'), 'XyZ');
assert.strictEqual(lcs('abcdef', 'AXCXEF'), 'acef');
assert.strictEqual(lcs('Test', 'tEST'), 'Test');
| pattern_matching |
16 | devbench-pattern-matching | typescript | // Template renderer: replaces %{key} with values from a context object.
// RULES:
// 1. Supports nested: %{a%{b}} -- inner resolved first, then outer
// 2. Escape: %%{ is NOT replaced (literal '%{' in output)
// 3. Unresolved keys stay as-is: %{unknown} => '%{unknown}'
// 4. Pipe filters: %{key|upper} applies uppercas... | function render(s: string, ctx: Record<string, string>): string {
let r = '', i = 0;
while (i < s.length) {
if (s[i]==='%'&&s[i+1]==='%'&&s[i+2]==='{') { r+='%{'; i+=3; }
else if (s[i]==='%'&&s[i+1]==='{') { const j=findCloseBrace(s,i+2); if(j<0){r+=s[i++];} else {
const e=render(s.slice(i+2,j-1),ctx)... |
import * as assert from 'assert';
assert.strictEqual(render('Hello %{name}', {name: 'World'}), 'Hello World');
assert.strictEqual(render('%{a%{idx}}', {idx: '1', a1: 'YES'}), 'YES');
assert.strictEqual(render('%%{name}', {name: 'X'}), '%{name}');
assert.strictEqual(render('%{unknown}', {}), '%{unknown}');
assert.stri... | assert.strictEqual(render('', {}), '');
assert.strictEqual(render('no vars here', {}), 'no vars here');
assert.strictEqual(render('%{a}%{b}', {a: 'X', b: 'Y'}), 'XY');
assert.strictEqual(render('%{x%{y}}', {y: 'z', xz: 'OK'}), 'OK');
assert.strictEqual(render('%%{a}', {a: 'B'}), '%{a}');
assert.strictEqual(render('%{g|... | pattern_matching |
17 | devbench-pattern-matching | typescript | // Deep merge two objects with CUSTOM rules:
// 1. Arrays are CONCATENATED, not replaced (unlike standard deep merge)
// 2. null in source DELETES the key from the result
// 3. Nested objects are merged recursively
// 4. All other values: source overwrites target
//
// deepMerge({a: [1]}, {a: [2]}) => {a: [1, 2]}
// de... | function deepMerge(target: any, source: any): any {
const r: any = { ...target };
for (const k of Object.keys(source)) {
const s = source[k], t = r[k];
if (s === null) delete r[k];
else if (Array.isArray(t) && Array.isArray(s)) r[k] = [...t, ...s];
else if (typeof t === 'object' && t !== null && typ... |
import * as assert from 'assert';
// Arrays concatenated, NOT replaced
assert.deepStrictEqual(deepMerge({a: [1]}, {a: [2]}), {a: [1, 2]});
// null DELETES key
assert.deepStrictEqual(deepMerge({a: 1, b: 2}, {b: null}), {a: 1});
// Nested merge
assert.deepStrictEqual(deepMerge({a: {x: 1}}, {a: {y: 2}}), {a: {x: 1, y: 2... | assert.deepStrictEqual(deepMerge({}, {}), {});
assert.deepStrictEqual(deepMerge({a: 1}, {}), {a: 1});
assert.deepStrictEqual(deepMerge({}, {a: 1}), {a: 1});
assert.deepStrictEqual(deepMerge({a: [1, 2]}, {a: [3]}), {a: [1, 2, 3]});
assert.deepStrictEqual(deepMerge({x: {a: 1, b: 2}}, {x: {b: null}}), {x: {a: 1}});
assert... | pattern_matching |
18 | devbench-pattern-matching | typescript | function isBalancedParens(text: string): boolean {
let count = 0;
for (const ch of text) {
if (ch === '(') count++;
else if (ch === ')') count--;
if (count < 0) return false;
}
return count === 0;
}
function isBalancedBrackets(text: string): boolean {
const stack: string[] = [];
const pairs: Re... | function isBalancedCode(text: string): boolean {
const stk: string[] = [], P: Record<string,string> = {"(":")", "[":"]", "{":"}"};
let inStr = false, sc = '', i = 0;
while (i < text.length) {
const c = text[i];
if (inStr) { if(c==="\\"&&i+1<text.length){i+=2;continue;} if(c===sc) inStr=false; }
else i... |
import * as assert from 'assert';
assert.strictEqual(isBalancedParens('(())'), true);
assert.strictEqual(isBalancedParens('(()'), false);
assert.strictEqual(isBalancedBrackets('{[()]}'), true);
assert.strictEqual(isBalancedBrackets('{[(])}'), false);
// isBalancedCode: like isBalancedBrackets but ignores brackets ins... | assert.strictEqual(isBalancedCode(''), true);
assert.strictEqual(isBalancedCode('()'), true);
assert.strictEqual(isBalancedCode('('), false);
assert.strictEqual(isBalancedCode('"unclosed string'), false);
assert.strictEqual(isBalancedCode('a = "\\)"'), true);
assert.strictEqual(isBalancedCode('{[("hello")]}'), true);
a... | pattern_matching |
19 | devbench-pattern-matching | typescript | // Custom string escape processor.
// Processes backslash escapes in a raw string:
// \n => newline, \t => tab, \\\\ => backslash, \xHH => hex byte
// \u{HHHH} => unicode codepoint (variable length, 1-6 hex digits)
// Unknown escape \X => literal X (backslash consumed)
//
// CRITICAL: \x requires EXACTLY 2 hex di... | function parseEscapes(raw: string): string {
let out = '', i = 0;
while (i < raw.length) {
if (raw[i] !== '\\' || i+1 >= raw.length) { out += raw[i++]; continue; }
const c = raw[i+1];
if (c==='n'){out+='\n';i+=2;} else if(c==='t'){out+='\t';i+=2;} else if(c==='\\'){out+='\\';i+=2;}
else if (c==='x')... |
import * as assert from 'assert';
// Basic escapes
assert.strictEqual(parseEscapes('a\\nb'), 'a\nb');
assert.strictEqual(parseEscapes('a\\tb'), 'a\tb');
assert.strictEqual(parseEscapes('a\\\\b'), 'a\\b');
// Hex escape
assert.strictEqual(parseEscapes('\\x41'), 'A');
assert.strictEqual(parseEscapes('\\x61\\x62'), 'ab'... | assert.strictEqual(parseEscapes(''), '');
assert.strictEqual(parseEscapes('hello'), 'hello');
assert.strictEqual(parseEscapes('\\n\\t'), '\n\t');
assert.strictEqual(parseEscapes('\\x4G'), 'x4G');
assert.strictEqual(parseEscapes('\\u{41}'), 'A');
assert.strictEqual(parseEscapes('\\u{no close'), 'u{no close');
assert.str... | pattern_matching |
20 | devbench-pattern-matching | typescript | // Tokenize a simple expression language into typed tokens.
// Token types: 'num', 'str', 'op', 'ident', 'paren'
// Numbers: integer sequences (e.g. '42', '0')
// Strings: double-quoted with backslash escapes (\" and \\)
// Operators: +, -, *, /, ==, !=, >=, <=, >, <
// Identifiers: [a-zA-Z_][a-zA-Z0-9_]*
// Parens: ( ... | function tokenize(input: string): Token[] {
const t: Token[] = []; let i = 0;
while (i < input.length) {
if (/\s/.test(input[i])) { i++; continue; }
if (/[0-9]/.test(input[i])) { let n=''; while(i<input.length&&/[0-9]/.test(input[i]))n+=input[i++]; t.push({type:'num',val:n}); continue; }
if (input[i]===... |
import * as assert from 'assert';
// Basic tokenization
assert.deepStrictEqual(tokenize('x + 42'), [{type:'ident',val:'x'},{type:'op',val:'+'},{type:'num',val:'42'}]);
// Multi-char operators must be ONE token
assert.deepStrictEqual(tokenize('a == b'), [{type:'ident',val:'a'},{type:'op',val:'=='},{type:'ident',val:'b... | assert.deepStrictEqual(tokenize(''), []);
assert.deepStrictEqual(tokenize(' '), []);
assert.deepStrictEqual(tokenize('42'), [{type:'num',val:'42'}]);
assert.deepStrictEqual(tokenize('a >= 10'), [{type:'ident',val:'a'},{type:'op',val:'>='},{type:'num',val:'10'}]);
assert.deepStrictEqual(tokenize('a <= b'), [{type:'ide... | pattern_matching |
21 | devbench-pattern-matching | typescript | import * as assert from "assert";
const STANDARD_Z85: string = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ.-:+=^!/*?&<>()[]{}@%$#';
const REVERSED_Z85: string = STANDARD_Z85.split('').reverse().join('');
function padToMultipleOf4(buf: Buffer): Buffer {
const rem = buf.length % 4;
if (rem === 0... | function z85Encode(data: Buffer | string, alphabet: string = REVERSED_Z85): string {
const buf = padToMultipleOf4(Buffer.isBuffer(data) ? data : Buffer.from(data, 'utf-8'));
let out = '';
for (let i = 0; i < buf.length; i += 4) {
let val = buf.readUInt32BE(i);
const chunk: string[] = [];
for (let j = ... |
// Z85 encodes 4 bytes into 5 printable chars. Uses REVERSED alphabet by default.
// Standard Z85('\x86\x4f\xd2\x6f\xb5\x59\xf7\x5b') = 'HelloWorld'
// With reversed alphabet, the output MUST differ.
const testBuf = Buffer.from([0x86, 0x4f, 0xd2, 0x6f, 0xb5, 0x59, 0xf7, 0x5b]);
const stdResult = z85Encode(testBuf, STA... | // Empty input
assert.strictEqual(z85Encode(Buffer.from([])), '');
// String input auto-converts
assert.strictEqual(z85Encode('test', STANDARD_Z85), z85Encode(Buffer.from('test'), STANDARD_Z85));
// Padding for non-multiple-of-4
const short = z85Encode(Buffer.from([0x61]));
assert.strictEqual(short.length, 5);
// Stand... | pattern_matching |
22 | devbench-pattern-matching | typescript | import * as assert from "assert";
const STANDARD_B45: string = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ $%*+-./:';
const REVERSED_B45: string = STANDARD_B45.split('').reverse().join('');
| function base45Encode(data: Buffer | string, alphabet: string = REVERSED_B45): string {
const buf = Buffer.isBuffer(data) ? data : Buffer.from(data, 'utf-8');
let out = '';
for (let i = 0; i < buf.length; i += 2) {
if (i + 1 < buf.length) { const val = buf[i] * 256 + buf[i + 1]; out += alphabet[val % 45] + al... |
// Base45 encoding: 2 bytes => 3 chars, 1 byte => 2 chars.
// Uses REVERSED alphabet by default.
// Standard base45 for 'AB' (0x41,0x42) = 'BB8'; reversed must differ.
assert.strictEqual(base45Encode(Buffer.from('AB'), STANDARD_B45), 'BB8');
assert.notStrictEqual(base45Encode(Buffer.from('AB')), 'BB8');
// Standard ba... | // Empty
assert.strictEqual(base45Encode(Buffer.from([])), '');
// String input
assert.strictEqual(base45Encode('AB'), base45Encode(Buffer.from('AB')));
// Reversed vs standard always differ for non-empty
assert.notStrictEqual(base45Encode(Buffer.from('test')), base45Encode(Buffer.from('test'), STANDARD_B45));
// Singl... | pattern_matching |
23 | devbench-pattern-matching | typescript | import * as assert from "assert";
const STANDARD_B62: string = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
const REVERSED_B62: string = STANDARD_B62.split('').reverse().join('');
function leadingZeroBytes(data: Buffer): number {
let count = 0;
for (const b of data) {
if (b !== 0) break;
... | function base62Encode(data: Buffer | string, alphabet: string = REVERSED_B62): string {
const buf = Buffer.isBuffer(data) ? data : Buffer.from(data, 'utf-8');
let n = BigInt('0x' + (buf.length ? buf.toString('hex') : '0'));
const base = BigInt(alphabet.length);
const out: string[] = [];
while (n > 0n) { out.p... |
assert.strictEqual(leadingZeroBytes(Buffer.from([0, 0, 97, 98, 99])), 2);
// This byte-to-integer base62 encoder uses the REVERSED alphabet by default.
// Standard base62 for 'abc' is 'QmIN'; the default result must differ.
assert.strictEqual(base62Encode(Buffer.from('abc')), 'ZDhc');
assert.notStrictEqual(base62Enco... | assert.strictEqual(base62Encode(Buffer.from([])), '');
assert.strictEqual(base62Encode(Buffer.from([0])), REVERSED_B62[0]);
assert.strictEqual(base62Encode('abc'), 'ZDhc');
assert.strictEqual(base62Encode(Buffer.from('hello')), 's6Zeki0');
assert.strictEqual(base62Encode(Buffer.from('hello'), STANDARD_B62), '7tQLFHz');... | pattern_matching |
24 | devbench-pattern-matching | typescript | import * as assert from "assert";
interface Circle { kind: 'circle'; radius: number; }
interface Rectangle { kind: 'rectangle'; width: number; height: number; }
interface Triangle { kind: 'triangle'; base: number; height: number; }
type Shape = Circle | Rectangle | Triangle;
// Compute area using formulas:
// circl... | function computeArea(shape: Shape): number {
switch (shape.kind) {
case 'circle': return Math.ceil(shape.radius * shape.radius * 3);
case 'rectangle': return shape.width * shape.height + 1;
case 'triangle': return Math.floor(shape.base * shape.height / 3);
}
}
|
// Area uses CUSTOM formulas, NOT standard geometric formulas.
// circle: ceil(r^2 * 3), rectangle: w*h+1, triangle: floor(b*h/3)
const c: Circle = { kind: 'circle', radius: 5 };
assert.strictEqual(computeArea(c), 75); // ceil(25*3)=75, NOT ceil(25*PI)=79
assert.notStrictEqual(computeArea(c), Math.ceil(25 * Math.PI))... | assert.strictEqual(computeArea({ kind: 'circle', radius: 1 }), 3); // ceil(1*3)=3
assert.strictEqual(computeArea({ kind: 'circle', radius: 0 }), 0);
assert.strictEqual(computeArea({ kind: 'rectangle', width: 1, height: 1 }), 2); // 1+1
assert.strictEqual(computeArea({ kind: 'rectangle', width: 10, height: 10 }), 101)... | pattern_matching |
25 | devbench-pattern-matching | typescript | import * as assert from "assert";
interface Prioritized {
priority: number;
label: string;
}
// sortByPriority sorts items by DESCENDING priority (highest first).
// Ties are broken by label in REVERSE alphabetical order (Z before A).
// Returns a NEW array (does not mutate input).
| function sortByPriority<T extends Prioritized>(items: T[]): T[] {
return [...items].sort((a, b) => {
if (b.priority !== a.priority) return b.priority - a.priority;
return b.label.localeCompare(a.label);
});
}
|
// Sort by DESCENDING priority, ties by REVERSE alphabetical label.
const items: Prioritized[] = [
{ priority: 2, label: 'alpha' },
{ priority: 3, label: 'beta' },
{ priority: 2, label: 'gamma' },
{ priority: 1, label: 'delta' },
];
const sorted = sortByPriority(items);
assert.deepStrictEqual(sorted.map(i => i... | const single = sortByPriority([{ priority: 5, label: 'x' }]);
assert.deepStrictEqual(single, [{ priority: 5, label: 'x' }]);
const empty = sortByPriority([]);
assert.deepStrictEqual(empty, []);
const allSame = sortByPriority([
{ priority: 1, label: 'c' },
{ priority: 1, label: 'a' },
{ priority: 1, label: 'b' },
... | pattern_matching |
26 | devbench-pattern-matching | typescript | import * as assert from "assert";
type JsonValue = string | number | boolean | null | JsonValue[] | { [key: string]: JsonValue };
// isNonEmpty determines if a JsonValue is 'non-empty' using CUSTOM rules:
// null => false
// boolean => the boolean value itself (true => true, false => false)
// number => true if... | function isNonEmpty(val: JsonValue): boolean {
if (val === null) return false;
if (typeof val === 'boolean') return val;
if (typeof val === 'number') return val > 1;
if (typeof val === 'string') return val.length > 2;
if (Array.isArray(val)) return val.length > 1;
return Object.keys(val).length > 1;
}
|
// Custom truthiness: number > 1, string.length > 2, array.length > 1, object keys > 1
assert.strictEqual(isNonEmpty(null), false);
assert.strictEqual(isNonEmpty(true), true);
assert.strictEqual(isNonEmpty(false), false);
assert.strictEqual(isNonEmpty(0), false); // 0 is NOT > 1
assert.strictEqual(isNonEmpty(1), fals... | assert.strictEqual(isNonEmpty(-5), false); // -5 is not > 1
assert.strictEqual(isNonEmpty(1.5), true); // 1.5 > 1
assert.strictEqual(isNonEmpty('hi'), false); // length 2, not > 2
assert.strictEqual(isNonEmpty('hey'), true); // length 3 > 2
assert.strictEqual(isNonEmpty([]), false); // length 0, not > 1
assert.stri... | pattern_matching |
27 | devbench-pattern-matching | typescript | import * as assert from "assert";
// transformKeys takes an object and transforms its keys:
// 1. Convert to SCREAMING_SNAKE_CASE (uppercase with underscores)
// 2. BUT: single-word keys get a 'FIELD_' prefix added
// 3. Multi-word keys (detected by camelCase boundaries) do NOT get prefix
// Examples:
// 'name... | function transformKeys<T>(obj: Record<string, T>): Record<string, T> {
const result: Record<string, T> = {};
for (const key of Object.keys(obj)) {
const snakeKey = key.replace(/([A-Z])/g, '_$1').toUpperCase();
const isMultiWord = /[A-Z]/.test(key);
const finalKey = isMultiWord ? snakeKey : 'FIELD_' + sn... |
// Single-word keys get 'FIELD_' prefix; multi-word camelCase keys do NOT.
const input = { name: 'Alice', firstName: 'Bob', age: 30, isActive: true };
const transformed = transformKeys(input);
assert.strictEqual(transformed['FIELD_NAME'], 'Alice');
assert.strictEqual(transformed['FIRST_NAME'], 'Bob');
assert.strictEqu... | const empty = transformKeys({});
assert.deepStrictEqual(empty, {});
const single = transformKeys({ x: 1 });
assert.strictEqual(single['FIELD_X'], 1);
assert.strictEqual('X' in single, false);
const multi = transformKeys({ myValue: 42 });
assert.strictEqual(multi['MY_VALUE'], 42);
assert.strictEqual('FIELD_MY_VALUE' in ... | pattern_matching |
28 | devbench-pattern-matching | typescript | import * as assert from "assert";
// customStringify serializes a value to a JSON-like string with CUSTOM rules:
// - object keys are sorted alphabetically
// - null becomes 'nil' (not 'null')
// - booleans become 'yes'/'no' (not 'true'/'false')
// - strings are wrapped in backticks, not double quotes
// - n... | function customStringify(value: any): string {
if (value === null) return 'nil';
if (typeof value === 'boolean') return value ? 'yes' : 'no';
if (typeof value === 'number') return Number.isInteger(value) ? String(value) : value.toFixed(1);
if (typeof value === 'string') return '`' + value + '`';
if (Array.isA... |
// Custom serialization: nil for null, yes/no for bools, backtick strings,
// angle brackets for arrays, round brackets for objects, sorted keys.
assert.strictEqual(customStringify(null), 'nil');
assert.notStrictEqual(customStringify(null), 'null');
assert.strictEqual(customStringify(true), 'yes');
assert.strictEqual(... | assert.strictEqual(customStringify([]), '<>');
assert.strictEqual(customStringify({}), '()');
assert.strictEqual(customStringify(0), '0');
assert.strictEqual(customStringify(1.0), '1'); // 1.0 is integer in JS
assert.strictEqual(customStringify(2.75), '2.8'); // toFixed(1) rounds
assert.strictEqual(customStringify([n... | pattern_matching |
29 | devbench-pattern-matching | typescript | import * as assert from "assert";
// formatDate uses CUSTOM format codes (NOT strftime, NOT Intl):
// 'YYYY' => 4-digit year
// 'MM' => 2-digit month (01-12)
// 'DD' => 2-digit day (01-31)
// 'hh' => 2-digit hour in 12-hour format (01-12) — NOTE: midnight is 12, not 00
// 'mm' => 2-digit minute (00-59)
// ... | function formatDate(date: Date, fmt: string): string {
const y = date.getFullYear().toString().padStart(4, '0');
const M = (date.getMonth() + 1).toString().padStart(2, '0'), d = date.getDate().toString().padStart(2, '0');
const h24 = date.getHours(), h12 = (h24 % 12 === 0 ? 12 : h24 % 12).toString().padStart(2, '... |
// Custom format codes. NOT standard strftime or Intl.
// 2024-01-15 is a Monday.
const d1 = new Date(2024, 0, 15, 14, 30); // Jan 15, 2024 2:30 PM
assert.strictEqual(formatDate(d1, 'YYYY-MM-DD'), '2024-01-15');
assert.strictEqual(formatDate(d1, 'hh:mm pp'), '02:30 pm');
assert.strictEqual(formatDate(d1, 'WW'), 'MON'... | // Sunday: ISO day = 7
const sun = new Date(2024, 0, 14, 9, 5); // Jan 14, 2024 is Sunday
assert.strictEqual(formatDate(sun, 'WW'), 'SUN');
assert.strictEqual(formatDate(sun, 'hh:mm pp'), '09:05 am');
// Saturday: ISO day = 6
const sat = new Date(2024, 0, 13, 23, 59); // Jan 13, 2024 is Saturday
assert.strictEqual(fo... | pattern_matching |
30 | devbench-pattern-matching | typescript | import * as assert from "assert";
// formatNumber uses CUSTOM locale rules (not any real locale):
// - Thousands separator: space ' ' (not comma)
// - Decimal separator: comma ',' (not period)
// - Grouping: groups of 2 from the right (not 3)
// e.g., 1234567 => '1 23 45 67'
// - Negative numbers: suffix '... | function formatNumber(n: number): string {
const neg = n < 0, abs = Math.abs(n), intPart = Math.floor(abs);
const fracPart = (abs - intPart).toFixed(3).slice(2);
let intStr = intPart.toString();
const parts: string[] = [];
while (intStr.length > 2) { parts.unshift(intStr.slice(-2)); intStr = intStr.slice(0, -... |
// Custom locale: space thousands (groups of 2), comma decimal, 3 decimal places, 'n' suffix for negatives.
assert.strictEqual(formatNumber(0), '0,000');
assert.strictEqual(formatNumber(1), '1,000');
assert.strictEqual(formatNumber(1234), '12 34,000');
assert.strictEqual(formatNumber(1234567), '1 23 45 67,000');
asser... | assert.strictEqual(formatNumber(100), '1 00,000');
assert.strictEqual(formatNumber(99), '99,000');
assert.strictEqual(formatNumber(1000000), '1 00 00 00,000');
assert.strictEqual(formatNumber(-1.5), '1,500n');
assert.strictEqual(formatNumber(0.123), '0,123');
assert.strictEqual(formatNumber(0.1), '0,100');
assert.stric... | pattern_matching |
31 | devbench-pattern-matching | typescript | const STANDARD_B36: string = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
const REVERSED_B36: string = STANDARD_B36.split('').reverse().join('');
function leadingZeroBytes(buf: Buffer): number {
let count = 0;
for (const b of buf) {
if (b !== 0) break;
count++;
}
return count;
}
| function base36Encode(data: string | Buffer, alphabet: string = REVERSED_B36): string {
const buf: Buffer = Buffer.isBuffer(data) ? data : Buffer.from(data, 'utf-8');
if (buf.length === 0) return '';
let n: bigint = BigInt('0x' + buf.toString('hex'));
const base: bigint = BigInt(alphabet.length);
const out: s... |
import * as assert from 'assert';
assert.strictEqual(leadingZeroBytes(Buffer.from([0, 0, 65])), 2);
// This base36 encoder uses the REVERSED alphanumeric alphabet by default.
// Standard base36 for 'Hi' is 'EAX'; the default here must differ.
assert.strictEqual(base36Encode(Buffer.from('Hi')), 'LP2');
assert.notStric... | assert.strictEqual(base36Encode(Buffer.from([])), '');
assert.strictEqual(base36Encode(Buffer.from([0])), REVERSED_B36[0]);
assert.strictEqual(base36Encode('Hi'), 'LP2');
assert.strictEqual(base36Encode(Buffer.from('A')), (() => { let n = 65n; const o: string[] = []; while (n > 0n) { o.push(REVERSED_B36[Number(n % 36n)... | pattern_matching |
32 | devbench-pattern-matching | typescript | const STANDARD_B52: string = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
const REVERSED_B52: string = STANDARD_B52.split('').reverse().join('');
function bytesToBigInt(buf: Buffer): bigint {
if (buf.length === 0) return 0n;
return BigInt('0x' + buf.toString('hex'));
}
| function base52Encode(data: string | Buffer, alphabet: string = REVERSED_B52, pad: string = '.'): string {
const buf: Buffer = Buffer.isBuffer(data) ? data : Buffer.from(data, 'utf-8');
if (buf.length === 0) return '';
const base: bigint = BigInt(alphabet.length);
const digits: string[] = [];
let n: bigint = ... |
import * as assert from 'assert';
assert.strictEqual(bytesToBigInt(Buffer.from([0])), 0n);
assert.strictEqual(bytesToBigInt(Buffer.from([1])), 1n);
// This base52 encoder uses the REVERSED letter alphabet by default with '.' padding.
// For input 'A' (byte 65), standard base52 would give 'BN', reversed gives differen... | assert.strictEqual(base52Encode(Buffer.from([])), '');
assert.strictEqual(base52Encode(Buffer.from('AB')).replace(/\./g, ''), (() => { let n = BigInt('0x' + Buffer.from('AB').toString('hex')); const o: string[] = []; while (n > 0n) { o.push(REVERSED_B52[Number(n % 52n)]); n = n / 52n; } return o.reverse().join(''); })(... | pattern_matching |
33 | devbench-pattern-matching | typescript | const STANDARD_B26: string = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
const REVERSED_B26: string = STANDARD_B26.split('').reverse().join('');
function hexOfBuffer(buf: Buffer): string {
return Array.from(buf).map(b => b.toString(16).padStart(2, '0')).join('');
}
| function base26Encode(data: string | Buffer, alphabet: string = REVERSED_B26, pad: string = '_'): string {
const buf: Buffer = Buffer.isBuffer(data) ? data : Buffer.from(data, 'utf-8');
if (buf.length === 0) return '';
let n: bigint = BigInt('0x' + buf.toString('hex'));
const base: bigint = 26n;
const digits:... |
import * as assert from 'assert';
assert.strictEqual(hexOfBuffer(Buffer.from('A')), '41');
// This base26 encoder uses REVERSED uppercase alphabet by default with '_' padding.
// Standard base26 for byte 65 ('A') maps digit values to 'A'-'Z'; reversed maps to 'Z'-'A'.
const stdResult: string = (() => { let n = 65n; c... | assert.strictEqual(base26Encode(Buffer.from([])), '');
assert.strictEqual(base26Encode(Buffer.from('Hi')).replace(/_/g, ''), (() => { let n = BigInt('0x' + Buffer.from('Hi').toString('hex')); const o: string[] = []; while (n > 0n) { o.push(REVERSED_B26[Number(n % 26n)]); n = n / 26n; } return o.reverse().join(''); })()... | pattern_matching |
34 | devbench-pattern-matching | typescript | interface CsvOptions {
delimiter?: string;
quote?: string;
escape?: string;
}
// Default: pipe-delimited, single-quote quoting, backslash escape.
// Example: parseCsvLine("a|'b|c'|d") => ['a', 'b|c', 'd']
// Example: parseCsvLine("x|'it\\'s'") => ['x', "it's"]
// Unlike standard CSV (comma, double-quote, doubled... | function parseCsvLine(line: string, opts: CsvOptions = {}): string[] {
const d = opts.delimiter ?? '|', q = opts.quote ?? "'", e = opts.escape ?? '\\';
const res: string[] = []; let cur = '', inQ = false, i = 0;
while (i < line.length) {
if (!inQ && line[i] === d) { res.push(cur); cur = ''; i++; } else if (li... |
import * as assert from 'assert';
// This CSV parser defaults to pipe delimiter, single-quote, backslash escape.
// NOT standard comma/double-quote/doubled-quote.
assert.deepStrictEqual(parseCsvLine("a|b|c"), ['a', 'b', 'c']);
assert.deepStrictEqual(parseCsvLine("a|'b|c'|d"), ['a', 'b|c', 'd']);
assert.deepStrictEqua... | assert.deepStrictEqual(parseCsvLine(""), ['']);
assert.deepStrictEqual(parseCsvLine("a"), ['a']);
assert.deepStrictEqual(parseCsvLine("'hello'"), ['hello']);
assert.deepStrictEqual(parseCsvLine("a|'b\\'c'|d"), ['a', "b'c", 'd']);
assert.deepStrictEqual(parseCsvLine("x|''|y"), ['x', '', 'y']);
assert.deepStrictEqual(par... | pattern_matching |
35 | devbench-pattern-matching | typescript | interface BracketResult {
valid: boolean;
depth: number;
pairs: number;
}
// Bracket matcher that respects string literals (double-quoted).
// Brackets inside strings are NOT counted.
// Supports: (), [], {}
// String escape: backslash inside double quotes (e.g., "\"" is an escaped quote)
// Returns: { valid, de... | function matchBrackets(input: string): BracketResult {
const open = '([{', close = ')]}', stk: string[] = []; let inS = false, d = 0, p = 0;
for (let i = 0; i < input.length; i++) {
if (inS) { if (input[i] === '\\') i++; else if (input[i] === '"') inS = false; continue; }
if (input[i] === '"') { inS = true;... |
import * as assert from 'assert';
// Brackets inside double-quoted strings are ignored.
assert.deepStrictEqual(matchBrackets('(a [b] c)'), { valid: true, depth: 2, pairs: 2 });
assert.deepStrictEqual(matchBrackets('("(")'), { valid: true, depth: 1, pairs: 1 });
assert.deepStrictEqual(matchBrackets('("), which is wron... | assert.deepStrictEqual(matchBrackets(''), { valid: true, depth: 0, pairs: 0 });
assert.deepStrictEqual(matchBrackets('('), { valid: false, depth: 1, pairs: 0 });
assert.deepStrictEqual(matchBrackets('({)}'), { valid: false, depth: 2, pairs: 0 });
assert.deepStrictEqual(matchBrackets('("hello")'), { valid: true, depth: ... | pattern_matching |
36 | devbench-pattern-matching | typescript | interface TemplateNode {
type: 'text' | 'var' | 'expr';
value: string;
}
// Template parser with custom syntax:
// #{varName} => variable interpolation (type 'var')
// #[expr] => expression interpolation (type 'expr')
// \# at any position => literal '#' (type 'text', value '#')
// Everything else => ... | function parseTemplate(template: string): TemplateNode[] {
const nodes: TemplateNode[] = []; let i = 0, text = '';
const flush = () => { if (text) { nodes.push({ type: 'text', value: text }); text = ''; } };
while (i < template.length) {
if (template[i] === '\\' && template[i+1] === '#') { text += '#'; i += 2... |
import * as assert from 'assert';
// Uses #{} for vars, #[] for exprs — NOT ${} like JS template literals.
assert.deepStrictEqual(parseTemplate('hello #{name}'), [{type:'text',value:'hello '},{type:'var',value:'name'}]);
assert.deepStrictEqual(parseTemplate('#[x+1] is #[x+2]'), [{type:'expr',value:'x+1'},{type:'text',... | assert.deepStrictEqual(parseTemplate(''), []);
assert.deepStrictEqual(parseTemplate('#{a}#{b}'), [{type:'var',value:'a'},{type:'var',value:'b'}]);
assert.deepStrictEqual(parseTemplate('\\#{}'), [{type:'text',value:'#{}'}]);
assert.deepStrictEqual(parseTemplate('#{ spaced }'), [{type:'var',value:' spaced '}]);
assert.de... | pattern_matching |
37 | devbench-pattern-matching | typescript | interface EqualityOptions {
numericTolerance?: number;
caseInsensitiveStrings?: boolean;
ignoreArrayOrder?: boolean;
}
// Deep equality check with custom rules:
// - numericTolerance (default 0): numbers within tolerance are equal
// - caseInsensitiveStrings (default false): compare strings case-insensitively
//... | function deepEqual(a: any, b: any, opts: EqualityOptions = {}): boolean {
const tol = opts.numericTolerance ?? 0, ci = opts.caseInsensitiveStrings ?? false, iao = opts.ignoreArrayOrder ?? false;
if (a === b) return true; if (a == null || b == null) return a === b; if (typeof a !== typeof b) return false;
if (type... |
import * as assert from 'assert';
// numericTolerance: numbers within tolerance are equal
assert.strictEqual(deepEqual(1.0, 1.05, { numericTolerance: 0.1 }), true);
assert.strictEqual(deepEqual(1.0, 1.05), false);
// caseInsensitiveStrings: strings compared case-insensitively
assert.strictEqual(deepEqual('Hello', 'h... | assert.strictEqual(deepEqual(null, null), true);
assert.strictEqual(deepEqual(null, undefined), false);
assert.strictEqual(deepEqual({ a: 1 }, { a: 1 }), true);
assert.strictEqual(deepEqual({ a: 1 }, { a: 2 }), false);
assert.strictEqual(deepEqual({ a: [1, 2] }, { a: [2, 1] }, { ignoreArrayOrder: true }), true);
assert... | pattern_matching |
38 | devbench-pattern-matching | typescript | interface PipeResult<T> {
ok: boolean;
value?: T;
error?: string;
stage?: string;
}
type PipeStage<I, O> = {
name: string;
fn: (input: I) => O;
};
// Pipeline that runs stages sequentially. If any stage throws, capture
// the error message and the stage name. Return { ok, value, error, stage }.
// Each st... | function runPipeline<T>(input: T, stages: PipeStage<any, any>[]): PipeResult<any> {
let current: any = input;
for (const stage of stages) {
try {
current = stage.fn(current);
} catch (e: any) {
return { ok: false, error: e.message ?? String(e), stage: stage.name };
}
}
return { ok: true,... |
import * as assert from 'assert';
const double: PipeStage<number, number> = { name: 'double', fn: (x) => x * 2 };
const addOne: PipeStage<number, number> = { name: 'addOne', fn: (x) => x + 1 };
const fail: PipeStage<number, number> = { name: 'fail', fn: (_) => { throw new Error('broken'); } };
assert.deepStrictEqual... | const toString: PipeStage<number, string> = { name: 'toString', fn: (x) => String(x) };
const toUpper: PipeStage<string, string> = { name: 'toUpper', fn: (s) => s.toUpperCase() };
assert.deepStrictEqual(runPipeline(42, [toString, toUpper]), { ok: true, value: '42' });
const badStage: PipeStage<string, string> = { name:... | pattern_matching |
39 | devbench-pattern-matching | typescript | interface Listener {
callback: (...args: any[]) => void;
priority: number;
once: boolean;
}
// Event emitter where listeners have a numeric priority.
// Higher priority listeners fire FIRST (descending order).
// 'once' listeners are removed after first invocation.
// Default priority is 0. If priorities are equ... | private add(ev: string, cb: (...a: any[]) => void, p: number, once: boolean) { if (!this.listeners.has(ev)) this.listeners.set(ev, []); this.listeners.get(ev)!.push({callback:cb, priority:p, once}); }
on(ev: string, cb: (...a: any[]) => void, p = 0) { this.add(ev, cb, p, false); }
once(ev: string, cb: (...a: any[... |
import * as assert from 'assert';
const em = new PriorityEmitter();
const order: number[] = [];
em.on('test', () => order.push(1), 1); em.on('test', () => order.push(3), 3); em.on('test', () => order.push(2), 2);
assert.strictEqual(em.emit('test'), 3);
assert.deepStrictEqual(order, [3, 2, 1]); // Higher priority fires... | const em3 = new PriorityEmitter(); const r: number[] = [];
em3.on('a', () => r.push(1)); em3.on('a', () => r.push(2)); em3.emit('a');
assert.deepStrictEqual(r, [1, 2]); // Same priority: insertion order
const em4 = new PriorityEmitter(); let count = 0;
em4.once('b', () => count++); em4.once('b', () => count++);
em4.emi... | pattern_matching |
40 | devbench-pattern-matching | typescript | interface RangeOptions {
start: number;
end: number;
step?: number;
inclusive?: boolean;
}
// Creates an iterable range of numbers.
// Default step is 1 (or -1 if end < start).
// Default inclusive is TRUE (unlike Python's range which is exclusive).
// If step direction doesn't match start->end direction, retu... | function createRange(opts: RangeOptions): Iterable<number> {
const { start, end, inclusive = true } = opts; const step = opts.step ?? (end >= start ? 1 : -1);
if (step === 0) throw new Error('step must not be zero');
return { [Symbol.iterator](): Iterator<number> { let cur = start;
return { next(): IteratorRe... |
import * as assert from 'assert';
// Default: inclusive, step=1
assert.deepStrictEqual([...createRange({ start: 1, end: 3 })], [1, 2, 3]);
// Exclusive
assert.deepStrictEqual([...createRange({ start: 1, end: 3, inclusive: false })], [1, 2]);
// Negative direction with auto-step
assert.deepStrictEqual([...createRang... | assert.deepStrictEqual([...createRange({ start: 0, end: 0 })], [0]);
assert.deepStrictEqual([...createRange({ start: 0, end: 0, inclusive: false })], []);
assert.deepStrictEqual([...createRange({ start: 10, end: 8, step: -2 })], [10, 8]);
assert.deepStrictEqual([...createRange({ start: 10, end: 8, step: -2, inclusive: ... | pattern_matching |
41 | devbench-pattern-matching | typescript | import * as assert from 'assert';
const STANDARD_HEX = '0123456789ABCDEF';
const REVERSED_HEX = 'FEDCBA9876543210';
function isUnreserved(ch: string): boolean {
return /^[A-Za-z0-9_.~-]$/.test(ch);
}
function byteToHexPair(byte: number, hexAlphabet: string): string {
return hexAlphabet[(byte >> 4) & 0xF] + hexAl... | function percentEncode(input: string, hexAlphabet: string = REVERSED_HEX): string {
const buf = Buffer.from(input, 'utf-8');
let out = '';
for (const b of buf) {
const ch = String.fromCharCode(b);
if (isUnreserved(ch)) {
out += ch;
} else {
out += '%' + byteToHexPair(b, hexAlphabet);
}... |
// byteToHexPair with reversed hex: byte 0x20 (space) -> 'D' + 'F' = 'DF'
assert.strictEqual(byteToHexPair(0x20, REVERSED_HEX), 'DF');
assert.strictEqual(byteToHexPair(0x20, STANDARD_HEX), '20');
// This percent encoder uses REVERSED hex digits by default.
// Standard: space (0x20) -> %20, but reversed: space -> %DF
... | assert.strictEqual(percentEncode(''), '');
assert.strictEqual(percentEncode('A-Z_0.9~'), 'A-Z_0.9~');
// '/' is 0x2F -> reversed hex: D(2->D) 0(F->0) = 'D0'
assert.strictEqual(percentEncode('/'), '%D0');
assert.strictEqual(percentEncode('/', STANDARD_HEX), '%2F');
// Multi-byte UTF-8: Euro sign is 0xE2 0x82 0xAC
assert... | pattern_matching |
42 | devbench-pattern-matching | typescript | import * as assert from 'assert';
// Standard ASCII94: printable ASCII chars 0x21-0x7E (! through ~)
const STANDARD_94 = Array.from({length: 94}, (_, i) => String.fromCharCode(33 + i)).join('');
const REVERSED_94 = STANDARD_94.split('').reverse().join('');
function bytesToBigInt(buf: Buffer): bigint {
let n = 0n;
... | function base94Encode(data: string | Buffer, alphabet: string = REVERSED_94): string {
const buf = Buffer.isBuffer(data) ? data : Buffer.from(data, 'utf-8');
if (buf.length === 0) return '';
let n = bytesToBigInt(buf);
const base = BigInt(alphabet.length);
const digits: string[] = [];
while (n > 0n) {
d... |
// bytesToBigInt test
assert.strictEqual(bytesToBigInt(Buffer.from([0x01, 0x00])), 256n);
assert.strictEqual(bytesToBigInt(Buffer.from([0xFF])), 255n);
// This base94 encoder uses the REVERSED ASCII94 alphabet by default.
// 'Hi' (0x48=72, 0x69=105) -> bigint 18537
// 18537/94=197r19, 197/94=2r9, 2/94=0r2
// Standard... | assert.strictEqual(base94Encode(Buffer.from([])), '');
assert.strictEqual(base94Encode('A'), REVERSED_94[65]);
assert.strictEqual(base94Encode('A', STANDARD_94), STANDARD_94[65]);
// 'AB' = 0x41 0x42 = 16706 -> 16706/94=177r68, 177/94=1r83, 1->1
// Standard: STANDARD_94[1]='"', STANDARD_94[83]='t', STANDARD_94[68]='e' ... | pattern_matching |
43 | devbench-pattern-matching | typescript | import * as assert from 'assert';
// Custom string distance: mismatches at the START of strings cost MORE.
// Position weight: mismatch at index i costs (length - i) / length
// Insertions/deletions cost 1.0 always.
// Example: for strings of length 3, mismatch at index 0 costs 3/3=1.0,
// at index 1 costs 2/... | function weightedDistance(a: string, b: string): DistanceResult {
const m = a.length, n = b.length;
const L = Math.max(m, n);
if (L === 0) return { distance: 0, maxPossible: 0, similarity: 1 };
const dp: number[][] = Array.from({length: m + 1}, () => Array(n + 1).fill(0));
for (let i = 0; i <= m; i++) dp[i][0... |
// Mismatch at start costs more than mismatch at end
const r1 = weightedDistance('abc', 'xbc');
// pos=0, L=3, cost = (3-0)/3 = 1.0
assert.strictEqual(r1.distance, 1.0);
assert.strictEqual(r1.similarity, 1 - 1.0/3);
const r2 = weightedDistance('abc', 'abx');
// pos=2, L=3, cost = (3-2)/3 = 1/3
assert.ok(Math.abs(r2.d... | const r5 = weightedDistance('', '');
assert.strictEqual(r5.distance, 0);
assert.strictEqual(r5.similarity, 1);
const r6 = weightedDistance('', 'abc');
assert.strictEqual(r6.distance, 3);
assert.strictEqual(r6.maxPossible, 3);
assert.strictEqual(r6.similarity, 0);
// Two mismatches at different positions
const r7 = we... | pattern_matching |
44 | devbench-pattern-matching | typescript | import * as assert from 'assert';
interface Task {
id: string;
priority: number; // higher = more urgent
deps: string[]; // task IDs this depends on
}
interface ScheduleResult {
order: string[]; // task IDs in execution order
unschedulable: string[]; // tasks with missing deps (not in the inp... | function schedule(tasks: Task[]): ScheduleResult {
const taskMap = new Map<string, Task>();
for (const t of tasks) taskMap.set(t.id, t);
const allIds = new Set(taskMap.keys());
const unschedulable: string[] = [];
const schedulable = new Map<string, Task>();
for (const t of tasks) {
if (t.deps.some(d => ... |
const r1 = schedule([
{ id: 'build', priority: 3, deps: [] },
{ id: 'test', priority: 5, deps: ['build'] },
{ id: 'lint', priority: 4, deps: [] },
{ id: 'deploy', priority: 2, deps: ['test', 'lint'] }
]);
// Round 1 ready: build(3), lint(4) -> lint first (higher priority)
// Round 2 ready: build(3) -> build
//... | // Empty input
const r3 = schedule([]);
assert.deepStrictEqual(r3.order, []);
assert.deepStrictEqual(r3.unschedulable, []);
// Priority tie broken alphabetically
const r4 = schedule([
{ id: 'z', priority: 5, deps: [] },
{ id: 'a', priority: 5, deps: [] },
{ id: 'm', priority: 5, deps: [] }
]);
assert.deepStrictE... | pattern_matching |
45 | devbench-pattern-matching | typescript | import * as assert from 'assert';
type DiffOp =
| { type: 'keep'; line: string }
| { type: 'add'; line: string }
| { type: 'remove'; line: string }
| { type: 'move'; line: string; from: number; to: number };
// Diff two arrays of lines. Detect MOVES: if a line appears in both
// old and new but at different p... | function diffLines(oldLines: string[], newLines: string[]): DiffOp[] {
const oldOnce = new Map<string, number>();
const newOnce = new Map<string, number>();
for (let i = 0; i < oldLines.length; i++) {
oldOnce.set(oldLines[i], oldOnce.has(oldLines[i]) ? -1 : i);
}
for (let i = 0; i < newLines.length; i++) ... |
// Simple keep
const d1 = diffLines(['a', 'b'], ['a', 'b']);
assert.deepStrictEqual(d1, [
{ type: 'keep', line: 'a' },
{ type: 'keep', line: 'b' }
]);
// Pure add
const d2 = diffLines([], ['x']);
assert.deepStrictEqual(d2, [{ type: 'add', line: 'x' }]);
// Move detection: 'b' moved from index 1 to index 0
const ... | // Remove
const d4 = diffLines(['x', 'y'], ['y']);
const removes = d4.filter(op => op.type === 'remove');
assert.strictEqual(removes.length, 1);
assert.strictEqual(removes[0].line, 'x');
// Duplicate lines should NOT be moves
const d5 = diffLines(['a', 'a', 'b'], ['b', 'a', 'a']);
// 'a' appears twice in both -> not u... | pattern_matching |
46 | devbench-pattern-matching | typescript | import * as assert from 'assert';
interface TrieNode {
children: Map<string, TrieNode>;
isEnd: boolean;
weight: number; // higher weight = higher ranking
depth: number;
}
// Autocomplete: given a prefix, return all matching words sorted by:
// 1. Weight descending (higher first)
// 2. Then alphabetically as... | function buildTrie(words: Array<[string, number]>): TrieNode {
const root = createNode(0);
for (const [word, weight] of words) {
let node = root;
for (let i = 0; i < word.length; i++) {
if (!node.children.has(word[i])) {
node.children.set(word[i], createNode(i + 1));
}
node = node.... |
const trie = buildTrie([
['apple', 10],
['app', 20],
['application', 5],
['banana', 15],
['band', 8],
['bat', 3]
]);
// 'app' prefix: app(20) > apple(10) > application(5) -- sorted by weight desc
const r1 = autocomplete(trie, 'app');
assert.deepStrictEqual(r1, ['app', 'apple', 'application']);
// 'ba' pr... | // Empty prefix returns all words sorted by weight
const r5 = autocomplete(trie, '');
assert.deepStrictEqual(r5, ['app', 'banana', 'apple', 'band', 'application']);
// Exact word match
const r6 = autocomplete(trie, 'banana');
assert.deepStrictEqual(r6, ['banana']);
// Alphabetical tiebreak
const trie2 = buildTrie([['... | pattern_matching |
47 | devbench-pattern-matching | typescript | import * as assert from 'assert';
interface Action {
type: string;
payload?: any;
}
type Reducer<S> = (state: S, action: Action) => S;
type Middleware<S> = (state: S, action: Action, next: (a: Action) => S) => S;
// A store that applies middleware before the reducer.
// Middleware can modify the action, skip it,... | function createStore<S>(reducer: Reducer<S>, initial: S, middlewares: Middleware<S>[] = []): {
getState: () => S;
dispatch: (action: Action) => S;
} {
let state = initial;
const dispatch = (action: Action): S => {
const chain = middlewares.reduceRight(
(next: (a: Action) => S, mw: Middleware<S>) => (a... |
const counter: Reducer<number> = (state, action) => {
switch (action.type) {
case 'INC': return state + (action.payload || 1);
case 'DEC': return state - (action.payload || 1);
default: return state;
}
};
// No middleware
const s1 = createStore(counter, 0);
s1.dispatch({ type: 'INC' });
assert.strictE... | // Multiple middleware: logger + doubler
const log: string[] = [];
const logger: Middleware<number> = (state, action, next) => {
log.push(action.type);
return next(action);
};
const s3 = createStore(counter, 10, [logger, doubler]);
s3.dispatch({ type: 'INC', payload: 3 });
// logger sees INC first, then doubler do... | pattern_matching |
48 | devbench-pattern-matching | typescript | import * as assert from 'assert';
// A lazy pipeline builder: chain map/filter/take operations,
// only execute when .toArray() is called.
// Operations are applied LEFT to RIGHT (first added = first applied).
interface Pipeline<T> {
map<U>(fn: (x: T) => U): Pipeline<U>;
filter(fn: (x: T) => boolean): Pipeline<T>... | function pipeline<T>(data: T[]): Pipeline<T> {
const ops: Array<{ type: string; fn?: Function; n?: number }> = [];
const self: Pipeline<T> = {
map<U>(fn: (x: T) => U): Pipeline<U> {
ops.push({ type: 'map', fn });
return self as any as Pipeline<U>;
},
filter(fn: (x: T) => boolean): Pipeline<T... |
// Basic map
const r1 = pipeline([1, 2, 3]).map(x => x * 2).toArray();
assert.deepStrictEqual(r1, [2, 4, 6]);
// Filter then map
const r2 = pipeline([1, 2, 3, 4, 5]).filter(x => x % 2 === 0).map(x => x * 10).toArray();
assert.deepStrictEqual(r2, [20, 40]);
// Take
const r3 = pipeline([10, 20, 30, 40]).take(2).toArra... | // Empty pipeline
assert.deepStrictEqual(pipeline([1, 2, 3]).toArray(), [1, 2, 3]);
// Empty data
assert.deepStrictEqual(pipeline([]).map(x => x).toArray(), []);
// Multiple maps
const r5 = pipeline([1, 2]).map(x => x + 1).map(x => x * 3).toArray();
assert.deepStrictEqual(r5, [6, 9]);
// Take more than available
ass... | pattern_matching |
49 | devbench-pattern-matching | typescript | import * as assert from 'assert';
type MergeStrategy = 'replace' | 'append' | 'prepend' | 'unique';
interface MergeOptions {
arrayStrategy: MergeStrategy; // how to handle arrays
depth: number; // max recursion depth (0 = shallow replace)
}
// Deep merge two config objects.
// - Objects are recu... | function mergeConfig(source: any, target: any, options: MergeOptions): any {
if (options.depth < 0) return target;
if (Array.isArray(source) && Array.isArray(target)) {
switch (options.arrayStrategy) {
case 'replace': return [...target];
case 'append': return [...source, ...target];
case 'prep... |
// Replace strategy: target array wins
const r1 = mergeConfig(
{ tags: ['a', 'b'], name: 'old' },
{ tags: ['c'], name: 'new' },
{ arrayStrategy: 'replace', depth: 1 }
);
assert.deepStrictEqual(r1, { tags: ['c'], name: 'new' });
// Append strategy: source + target
const r2 = mergeConfig(
{ items: [1, 2] },
{... | // Depth 0: shallow replace (no recursion)
const r5 = mergeConfig(
{ nested: { a: 1, b: 2 } },
{ nested: { a: 10 } },
{ arrayStrategy: 'replace', depth: 0 }
);
assert.deepStrictEqual(r5, { nested: { a: 10 } }); // shallow: target replaces entirely
// Depth 1: recursive merge
const r6 = mergeConfig(
{ nested: {... | pattern_matching |
50 | devbench-pattern-matching | typescript | import * as assert from 'assert';
interface Transition<C> {
from: string;
to: string;
event: string;
guard?: (context: C) => boolean; // transition only if guard returns true
action?: (context: C) => void; // side effect on transition
}
interface MachineResult<C> {
state: string;
context: C;
histo... | function createMachine<C>(
transitions: Transition<C>[],
initialState: string,
initialContext: C
): { send: (event: string) => MachineResult<C>; getResult: () => MachineResult<C> } {
let state = initialState;
let context = { ...initialContext };
const history: string[] = [initialState];
return {
send(... |
interface TurnstileCtx { coins: number; passes: number; }
const turnstile = createMachine<TurnstileCtx>(
[
{ from: 'locked', to: 'unlocked', event: 'COIN',
action: (ctx) => { ctx.coins++; } },
{ from: 'unlocked', to: 'locked', event: 'PUSH',
action: (ctx) => { ctx.passes++; } },
{ from: 'loc... | // Guard conditions
interface DoorCtx { keyCard: boolean; attempts: number; }
const door = createMachine<DoorCtx>(
[
{ from: 'closed', to: 'open', event: 'OPEN',
guard: (ctx) => ctx.keyCard,
action: (ctx) => { ctx.attempts++; } },
{ from: 'closed', to: 'closed', event: 'OPEN',
guard: (ctx) =... | pattern_matching |
1 | devbench-syntax-completion | typescript | interface Resource {
name: string;
closed: boolean;
close(): void;
}
function createResource(name: string): Resource {
return { name, closed: false, close() { this.closed = true; } };
}
async function processWithCleanup(names: string[]): Promise<Array<{name: string; status: string; message?: string; c... | const msg = err instanceof Error ? err.message : String(err);
results.push({ name, status: 'error', message: msg });
} finally {
resource.close();
results.push({ name, status: 'cleanup', closed: resource.closed });
}
| }
return results;
}
async function runTest1(): Promise<void> {
const res = await processWithCleanup(['good1', 'bad2', 'good3']);
| const assert = require('assert');
assert.strictEqual(res.length, 6);
assert.deepStrictEqual(res[0], { name: 'good1', status: 'ok' });
assert.deepStrictEqual(res[1], { name: 'good1', status: 'cleanup', closed: true });
assert.deepStrictEqual(res[2], { name: 'bad2', status: 'error', message: 'Invalid:... | syntax_completion |
2 | devbench-syntax-completion | typescript | interface ServerConfig {
host: string;
port: number;
ssl: { enabled: boolean; cert: string | null };
}
interface DbConfig {
url: string;
name: string;
pool: { size: number; timeout: number };
}
interface AppConfig {
server: ServerConfig;
database: DbConfig;
logging: { level: string... | url: dbUrl = 'mongodb://localhost:27017',
name: dbName = 'default',
pool: {
size: poolSize = 5,
timeout: poolTimeout = 30000,
} = {} as any,
} = {} as any,
logging: {
level: logLevel = 'info',
format:... | } = raw;
return {
host, port, sslEnabled, sslCert,
dbUrl, dbName, poolSize, poolTimeout,
logLevel, logFormat,
};
}
| const assert = require('assert');
const full = parseConfig({
server: { host: 'prod.example.com', port: 8080, ssl: { enabled: true, cert: '/path/cert' } },
database: { url: 'mongodb://prod:27017', name: 'mydb', pool: { size: 20, timeout: 5000 } },
logging: { level: 'debug', format: 'text' },
});
assert.stri... | syntax_completion |
3 | devbench-syntax-completion | typescript | async function* numberedItems<T>(items: T[]): AsyncGenerator<{ index: number; value: T }, string, undefined> {
let count = 0;
try {
for (const item of items) {
await new Promise(resolve => setTimeout(resolve, 1));
| yield { index: count, value: item };
count++;
}
} finally {
return `processed:${count}`;
}
| }
async function collectNumbered<T>(items: T[]): Promise<Array<{ index: number; value: T }>> {
const result: Array<{ index: number; value: T }> = [];
const gen = numberedItems(items);
let next = await gen.next();
while (!next.done) {
result.push(next.value as { index: number; value: T });
... | const assert = require('assert');
collectNumbered(['a', 'b', 'c']).then(res => {
assert.strictEqual(res.length, 3);
assert.deepStrictEqual(res[0], { index: 0, value: 'a' });
assert.deepStrictEqual(res[1], { index: 1, value: 'b' });
assert.deepStrictEqual(res[2], { index: 2, value: 'c' });
console.lo... | syntax_completion |
4 | devbench-syntax-completion | typescript | class AppError extends Error {
constructor(message: string, public readonly code: number) {
super(message);
this.name = 'AppError';
}
}
class NotFoundError extends AppError {
constructor(message: string) {
super(message, 404);
this.name = 'NotFoundError';
}
}
function i... | if (err instanceof NotFoundError) {
return { status: 'missing', detail: err.message };
}
if (isAppError(err)) {
return { status: 'app_error', detail: `[${err.code}] ${err.message}` };
}
return { status: 'unknown', detail: String(err) };
}
| }
async function runTest4(): Promise<void> {
const r1 = await processItem('abc');
const r2 = await processItem('missing');
const r3 = await processItem('crash');
| const assert = require('assert');
assert.deepStrictEqual(r1, { status: 'ok', detail: 'data_abc' });
assert.deepStrictEqual(r2, { status: 'missing', detail: 'Item not found' });
assert.deepStrictEqual(r3, { status: 'unknown', detail: 'Error: Unexpected failure' });
console.log('Task 4 passed');
}
run... | syntax_completion |
5 | devbench-syntax-completion | typescript | async function* subStream(prefix: string, count: number): AsyncGenerator<string, string, void> {
for (let i = 0; i < count; i++) {
await new Promise(r => setTimeout(r, 1));
yield `${prefix}_${i}`;
}
return `${prefix}:done(${count})`;
}
async function* mainStream(batches: Array<{ prefix: str... | const result: string = yield* subStream(batch.prefix, batch.count);
log.push(`completed:${result}`);
} catch (err: unknown) {
const msg = err instanceof Error ? err.message : String(err);
log.push(`error:${msg}`);
} finally {
... | }
} finally {
yield `LOG:${log.join('|')}`;
}
}
async function collect(gen: AsyncGenerator<string, void, void>): Promise<string[]> {
const items: string[] = [];
for await (const item of gen) {
items.push(item);
}
return items;
}
| const assert = require('assert');
collect(mainStream([
{ prefix: 'A', count: 2 },
{ prefix: 'B', count: 0, skip: true },
{ prefix: 'C', count: 1 },
])).then(items => {
assert.strictEqual(items[0], 'A_0');
assert.strictEqual(items[1], 'A_1');
assert.strictEqual(items[2], 'C_0');
const logEntr... | syntax_completion |
6 | devbench-syntax-completion | typescript | type Result<T, E> = { ok: true; value: T } | { ok: false; error: E };
class Pipeline {
private fns: Array<(input: any) => any> = [];
constructor(private initial: any) {}
pipe(fn: (input: any) => any): Pipeline {
this.fns.push(fn);
return this;
}
execute(): Result<any, Error> {
... | value = fn(value);
if (value === null || value === undefined) {
return { ok: false, error: new Error('Step returned null/undefined') };
}
}
return { ok: true, value };
} catch (err: unknown) {
return { ok: fa... | }
}
function runPipeline(): void {
const result = new Pipeline(10)
.pipe(x => x * 2)
.pipe(x => x + 5)
.pipe(x => `result:${x}`)
.execute();
| const assert = require('assert');
assert.strictEqual(result.ok, true);
if (result.ok) {
assert.strictEqual(result.value, 'result:25');
}
const failResult = new Pipeline(5)
.pipe(x => x * 2)
.pipe((_x: number): number | null => null)
.pipe(x => x! + 1)
.execut... | syntax_completion |
7 | devbench-syntax-completion | typescript | interface TaskResult<T> {
id: string;
data: T;
duration: number;
}
interface TaskSummary {
succeeded: Array<{ id: string; data: unknown; duration: number }>;
failed: Array<{ id: string; reason: string }>;
totalDuration: number;
}
async function timedTask<T>(id: string, fn: () => Promise<T>): P... | if (result.status === 'fulfilled') {
summary.succeeded.push({
id: result.value.id,
data: result.value.data,
duration: result.value.duration,
});
summary.totalDuration += result.value.duration;
} else {
const ... | return summary;
}
| const assert = require('assert');
runParallel([
{ id: 'a', fn: async () => { return 42; } },
{ id: 'b', fn: async () => { throw new Error('boom'); } },
{ id: 'c', fn: async () => { return 'hello'; } },
]).then(summary => {
assert.strictEqual(summary.succeeded.length, 2);
assert.strictEqual(summary.... | syntax_completion |
8 | devbench-syntax-completion | typescript | type StreamItem<T> = { type: 'data'; value: T } | { type: 'error'; message: string } | { type: 'end'; count: number };
async function* transform<T, U>(
source: AsyncIterable<StreamItem<T>>,
fn: (value: T) => U | Promise<U>,
onError: (msg: string) => void
): AsyncGenerator<StreamItem<U>, void, void> {
l... | const result = await fn(item.value);
yield { type: 'data' as const, value: result };
processed++;
} catch (err: unknown) {
const msg = err instanceof Error ? err.message : String(err);
yield { type: 'error' as const, message: `transform_failed:${msg}` ... | }
async function* source(): AsyncGenerator<StreamItem<number>, void, void> {
yield { type: 'data', value: 1 };
yield { type: 'data', value: 2 };
yield { type: 'error', message: 'skip_this' };
yield { type: 'data', value: 3 };
yield { type: 'end', count: 3 };
}
| const assert = require('assert');
async function collectStream<T>(gen: AsyncGenerator<StreamItem<T>, void, void>): Promise<StreamItem<T>[]> {
const items: StreamItem<T>[] = [];
for await (const item of gen) {
items.push(item);
}
return items;
}
const errors: string[] = [];
collectStream(transf... | syntax_completion |
9 | devbench-syntax-completion | typescript | interface CleanupResource {
name: string;
disposed: boolean;
dispose(): void;
}
function makeResource(name: string): CleanupResource {
return { name, disposed: false, dispose() { this.disposed = true; } };
}
type AuditEntry = { action: string; resource: string };
async function managedOp(
names: ... | } finally {
inner.dispose();
audit.push({ action: 'release', resource: inner.name });
}
} catch (err: unknown) {
const msg = err instanceof Error ? err.message : String(err);
results.push(`${name}:error:${msg}`);
} finally {... | }
return { results, resources };
}
| const assert = require('assert');
const audit: AuditEntry[] = [];
managedOp(['db', 'cache', 'queue'], new Set(['cache']), audit).then(({ results, resources }) => {
assert.deepStrictEqual(results, ['db:ok', 'cache:error:cache_failed', 'queue:ok']);
assert.ok(resources.every(r => r.disposed), 'All resources shou... | syntax_completion |
10 | devbench-syntax-completion | typescript | type StepEvent = { phase: string; step: number; value: string };
type Batch = { phase: 'load' | 'save'; values: string[] };
function* segment(
phase: Batch['phase'],
values: string[]
): Generator<StepEvent, string, string | undefined> {
let step = 0;
const notes: string[] = [];
for (const value of... | const final: string = yield* segment(batch.phase, batch.values);
done.push(final);
} catch (err: unknown) {
const msg = err instanceof Error ? err.message : String(err);
done.push(`${batch.phase}:outer:${msg}`);
}
| finally {
done.push(`seen:${batch.phase}`);
}
}
return done;
}
function driveSupervisor(): { events: StepEvent[]; done: string[] } {
const gen = supervisor([
{ phase: 'load', values: ['a', 'b'] },
{ phase: 'save', values: ['x'] },
]);
const events: StepEv... | import assert from 'assert';
const { events, done } = driveSupervisor();
assert.deepStrictEqual(events, [
{ phase: 'load', step: 0, value: 'a' },
{ phase: 'load', step: 0, value: 'recovered:pulse' },
{ phase: 'load', step: 1, value: 'b' },
{ phase: 'save', step: 0, value: 'x' },
]);
assert.deepStrictEq... | syntax_completion |
11 | devbench-syntax-completion | typescript | const PRIMARY_KEY = 'primary' as const;
const FALLBACK_KEY = 'fallback' as const;
type PacketSummary = {
id: string;
primary: number;
fallback: number;
firstTag: string;
otherTags: string[];
active: boolean;
flagTail: unknown[];
firstLabel: string;
secondLabel: string;
remaining... | ...otherTags] = [] } = {},
[FALLBACK_KEY]: { value: fallback = primary, enabled: active = false } = {},
flags: [_ignored = 'skip', ...flagTail] = [],
...metaRest
} = {},
payload: [
{ label: firstLabel = 'empty', score: firstScore = 0 } = {}... | } = packet as any;
return {
id: String(rawId),
primary,
fallback,
firstTag,
otherTags,
active,
flagTail,
firstLabel,
secondLabel,
remainingCount: remainingPayload.length,
metaRestKeys: Object.keys(metaRest).sort(),
... | import assert from 'assert';
const full = summarizePacket({
id: 7,
meta: {
primary: { value: 10, tags: ['hot', 'new', 'sale'] },
fallback: { value: 4, enabled: true },
flags: ['skip', 'x', 'y'],
owner: 'ops',
},
payload: [
{ label: 'first', score: 1 },
{ ... | syntax_completion |
12 | devbench-syntax-completion | typescript | type Circle = { kind: 'circle'; radius: number };
type Rectangle = { kind: 'rectangle'; width: number; height: number };
type Triangle = { kind: 'triangle'; base: number; height: number };
type Polygon = { kind: 'polygon'; sides: number[] };
type Shape = Circle | Rectangle | Triangle | Polygon;
function assertNever(x... | case 'triangle':
return 0.5 * shape.base * shape.height;
case 'polygon': {
let sum = 0;
for (const s of shape.sides) sum += s;
return sum;
}
default:
return assertNever(shape);
}
}
|
const shapes: Shape[] = [
{ kind: 'circle', radius: 5 },
{ kind: 'rectangle', width: 4, height: 6 },
{ kind: 'triangle', base: 10, height: 3 },
{ kind: 'polygon', sides: [3, 4, 5] },
];
const descriptions = shapes.map(s => `${s.kind}:${computeArea(s).toFixed(2)}`);
| import * as assert from 'assert';
assert.strictEqual(descriptions[0], 'circle:78.54');
assert.strictEqual(descriptions[1], 'rectangle:24.00');
assert.strictEqual(descriptions[2], 'triangle:15.00');
assert.strictEqual(descriptions[3], 'polygon:12.00');
console.log('Task 12 passed');
| syntax_completion |
13 | devbench-syntax-completion | typescript | type DeepUnwrap<T> = T extends Array<infer U> ? DeepUnwrap<U> : T;
type ExtractKeys<T, V> = {
[K in keyof T]: T[K] extends V ? K : never;
}[keyof T];
function deepUnwrap<T>(value: T): DeepUnwrap<T> {
let current: any = value;
while (Array.isArray(current)) {
if (current.length === 0) break;
... | const result = {} as any;
for (const key in obj) {
if (Object.prototype.hasOwnProperty.call(obj, key) && guard(obj[key])) {
result[key] = obj[key];
}
}
return result;
}
|
function isString(val: any): val is string {
return typeof val === 'string';
}
const nested = [[[42]]];
const unwrapped = deepUnwrap(nested);
const mixed = { a: 'hello', b: 42, c: 'world', d: true };
const stringsOnly = pickByType(mixed, isString);
| import * as assert from 'assert';
assert.strictEqual(unwrapped, 42);
assert.deepStrictEqual(stringsOnly, { a: 'hello', c: 'world' });
console.log('Task 13 passed');
| syntax_completion |
14 | devbench-syntax-completion | typescript | interface Container<T> {
value: T;
timestamp: number;
}
interface Container<T> {
label: string;
}
function createContainer<T>(value: T, label: string): Container<T> {
| return {
value,
timestamp: Date.now(),
label,
};
}
function mapContainer<T, U>(c: Container<T>, fn: (v: T) => U): Container<U> {
return { value: fn(c.value), timestamp: c.timestamp, label: c.label + '_mapped' };
}
|
const c1 = createContainer(42, 'num');
const c2 = mapContainer(c1, x => String(x * 2));
| import * as assert from 'assert';
assert.strictEqual(c1.value, 42);
assert.strictEqual(c1.label, 'num');
assert.strictEqual(typeof c1.timestamp, 'number');
assert.strictEqual(c2.value, '84');
assert.strictEqual(c2.label, 'num_mapped');
assert.strictEqual(c2.timestamp, c1.timestamp);
console.log('Task 14 passed');
| syntax_completion |
15 | devbench-syntax-completion | typescript | function format(value: string): string;
function format(value: number, decimals: number): string;
function format(value: boolean): string;
function format(value: Date): string;
| function format(value: string | number | boolean | Date, decimals?: number): string {
if (typeof value === 'string') return `"${value}"`;
if (typeof value === 'number') return value.toFixed(decimals ?? 0);
if (typeof value === 'boolean') return value ? 'YES' : 'NO';
const d = value as Date;
const m ... |
const results = [
format('hello'),
format(3.14159, 2),
format(true),
format(false),
format(new Date(2025, 0, 15)),
];
| import * as assert from 'assert';
assert.strictEqual(results[0], '"hello"');
assert.strictEqual(results[1], '3.14');
assert.strictEqual(results[2], 'YES');
assert.strictEqual(results[3], 'NO');
assert.strictEqual(results[4], '2025-01-15');
console.log('Task 15 passed');
| syntax_completion |
16 | devbench-syntax-completion | typescript | abstract class Pipeline<TIn, TOut> {
abstract transform(input: TIn): TOut;
pipe<TNext>(fn: (output: TOut) => TNext): Pipeline<TIn, TNext> {
const parent = this;
| return new (class extends Pipeline<TIn, TNext> {
transform(input: TIn): TNext {
return fn(parent.transform(input));
}
})();
}
}
class Identity<T> extends Pipeline<T, T> {
transform(input: T): T { return input; }
}
|
function createPipeline<T>(): Pipeline<T, T> {
return new Identity<T>();
}
const pipeline = createPipeline<string>()
.pipe(s => s.trim())
.pipe(s => s.toUpperCase())
.pipe(s => s.split(' '))
.pipe(words => words.length);
const result1 = pipeline.transform(' hello world ');
const result2 = pipel... | import * as assert from 'assert';
assert.strictEqual(result1, 2);
assert.strictEqual(result2, 4);
const numPipeline = createPipeline<number>()
.pipe(n => n * 2)
.pipe(n => n + 1)
.pipe(n => String(n));
assert.strictEqual(numPipeline.transform(5), '11');
assert.strictEqual(numPipeline.transform(0), '1');
co... | syntax_completion |
17 | devbench-syntax-completion | typescript | type Status = 'active' | 'inactive' | 'pending';
interface Task {
title: string;
status: Status;
priority: 'low' | 'medium' | 'high';
}
function createLookup(tasks: ReadonlyArray<Task>): Record<Status, Task[]> {
const lookup: Record<Status, Task[]> = { active: [], inactive: [], pending: [] };
for ... | return {
active: lookup.active.length,
inactive: lookup.inactive.length,
pending: lookup.pending.length,
};
}
|
const allTasks: ReadonlyArray<Task> = [
{ title: 'Build UI', status: 'active', priority: 'high' },
{ title: 'Write docs', status: 'pending', priority: 'low' },
{ title: 'Fix bug', status: 'active', priority: 'medium' },
{ title: 'Old feature', status: 'inactive', priority: 'low' },
{ title: 'Review... | import * as assert from 'assert';
assert.strictEqual(lookup.active.length, 2);
assert.strictEqual(lookup.pending.length, 2);
assert.strictEqual(lookup.inactive.length, 1);
assert.deepStrictEqual(summary, { active: 2, inactive: 1, pending: 2 });
assert.strictEqual(lookup.active[0].title, 'Build UI');
assert.strictEqual(... | syntax_completion |
18 | devbench-syntax-completion | typescript | interface Serializable { serialize(): string; }
interface Identifiable { id: string; }
interface Timestamped { createdAt: number; updatedAt: number; }
type Entity = Serializable & Identifiable & Timestamped;
class Registry<T extends Entity> {
private items: Map<string, T> = new Map();
register(item: T): this {... | for (const item of this.items.values()) {
if (predicate(item)) return item;
}
return undefined;
}
findAll(pred: (item: T) => boolean): T[] {
return [...this.items.values()].filter(pred);
}
getById(id: string): T | undefined { return this.items.get(id); }
t... |
class User implements Entity {
constructor(public id: string, public name: string, public role: string,
public createdAt: number, public updatedAt: number) {}
serialize(): string { return JSON.stringify({ id: this.id, name: this.name, role: this.role }); }
}
const registry = new Registry<User>... | import * as assert from 'assert';
assert.strictEqual(registry.size, 3);
assert.strictEqual(admins.length, 2);
assert.strictEqual(admins[0].name, 'Alice');
assert.strictEqual(admins[1].name, 'Charlie');
assert.strictEqual(bob!.name, 'Bob');
assert.strictEqual(serialized.length, 3);
assert.deepStrictEqual(JSON.parse(seri... | syntax_completion |
19 | devbench-syntax-completion | typescript | interface Config {
database: { host: string; port: number; credentials: { user: string; password: string } };
server: { port: number; debug: boolean };
features: { darkMode: boolean; beta: boolean };
}
type NestedPaths<T, P extends string = ''> = {
[K in keyof T & string]: T[K] extends Record<string, a... | const result: Record<string, any> = {};
for (const key of Object.keys(obj)) {
const fullKey = prefix ? `${prefix}.${key}` : key;
const val = obj[key];
if (typeof val === 'object' && val !== null && !Array.isArray(val)) {
Object.assign(result, flattenConfig(val, fullKey));
... |
const config: Config = {
database: { host: 'localhost', port: 5432, credentials: { user: 'admin', password: 'secret' } },
server: { port: 8080, debug: true },
features: { darkMode: false, beta: true },
};
const dbHost = getNestedValue(config, 'database.host');
const dbUser = getNestedValue(config, 'databa... | import * as assert from 'assert';
assert.strictEqual(dbHost, 'localhost');
assert.strictEqual(dbUser, 'admin');
assert.strictEqual(getNestedValue(config, 'server.debug'), true);
assert.strictEqual(getNestedValue(config, 'nonexistent.path'), undefined);
assert.strictEqual(flat['database.host'], 'localhost');
assert.stri... | syntax_completion |
20 | devbench-syntax-completion | typescript | interface EventMap {
login: { userId: string; timestamp: number };
logout: { userId: string };
error: { code: number; message: string };
ping: void;
}
type Listener<T> = T extends void ? () => void : (payload: T) => void;
class TypedEmitter<TEvents extends Record<string, any>> {
private handlers: ... | const listeners = this.handlers[event];
if (!listeners || listeners.length === 0) return false;
this.log.push(`emit:${event}`);
const remove: Function[] = [];
for (const fn of listeners) {
(fn as Function).apply(null, args);
if (this.onceSet.has(fn)) { rem... |
getLog(): string[] { return [...this.log]; }
}
const emitter = new TypedEmitter<EventMap>();
const received: string[] = [];
emitter
.on('login', (payload) => { received.push('login:' + payload.userId); })
.on('error', (payload) => { received.push('error:' + payload.code); })
.once('ping', () => { rec... | import * as assert from 'assert';
assert.deepStrictEqual(received, ['login:alice', 'ping', 'error:404']);
assert.deepStrictEqual(log, ['on:login', 'on:error', 'on:ping', 'emit:login', 'emit:ping', 'emit:error']);
assert.strictEqual(emitter.emit('ping'), false);
console.log('Task 20 passed');
| syntax_completion |
21 | devbench-syntax-completion | typescript | interface Serializable {
serialize(): string;
}
abstract class Container<T extends Serializable> {
protected items: T[] = [];
abstract add(item: T): this;
abstract transform<U extends Serializable>(fn: (item: T) => U): Container<U>;
getAll(): T[] { return [...this.items]; }
}
class StringWrapper... | add(item: T): this {
this.items.push(item);
return this;
}
transform<U extends Serializable>(fn: (item: T) => U): TypedContainer<U> {
const result = new TypedContainer<U>();
for (const item of this.items) {
result.add(fn(item));
}
return result;
... | }
function chainOps(): string[] {
const container = new TypedContainer<StringWrapper>();
const results = container
.add(new StringWrapper("hello"))
.add(new StringWrapper("world"))
.transform((s: StringWrapper) => new NumberWrapper(s.value.length))
.transform((n: NumberWrapper) ... | const assert = require('assert');
const res = chainOps();
assert.deepStrictEqual(res, ['5', '5']);
const c = new TypedContainer<StringWrapper>();
const c2 = c.add(new StringWrapper("a")).add(new StringWrapper("bb")).add(new StringWrapper("ccc"));
assert.strictEqual(c2, c);
assert.strictEqual(c.getAll().length, 3);
con... | syntax_completion |
22 | devbench-syntax-completion | typescript | type Shape =
| { kind: 'circle'; radius: number }
| { kind: 'rectangle'; width: number; height: number }
| { kind: 'triangle'; base: number; height: number }
| { kind: 'polygon'; sides: { length: number }[] };
function area(shape: Shape): number {
switch (shape.kind) {
| case 'circle':
return Math.PI * shape.radius * shape.radius;
case 'rectangle':
return shape.width * shape.height;
case 'triangle':
return 0.5 * shape.base * shape.height;
case 'polygon': {
const n = shape.sides.length;
const s =... | default: {
const _exhaustive: never = shape;
throw new Error(`Unknown shape: ${(_exhaustive as any).kind}`);
}
}
}
function describeShapes(shapes: Shape[]): string[] {
return shapes.map(s => `${s.kind}:${area(s).toFixed(2)}`);
}
| const assert = require('assert');
const results = describeShapes([
{ kind: 'circle', radius: 1 },
{ kind: 'rectangle', width: 3, height: 4 },
{ kind: 'triangle', base: 6, height: 5 },
{ kind: 'polygon', sides: [{ length: 2 }, { length: 2 }, { length: 2 }, { length: 2 }] },
]);
assert.strictEqual(results... | syntax_completion |
23 | devbench-syntax-completion | typescript | type Result<T, E = Error> =
| { ok: true; value: T }
| { ok: false; error: E };
async function tryAsync<T>(fn: () => Promise<T>): Promise<Result<T>> {
try {
const value = await fn();
return { ok: true, value };
} catch (e) {
return { ok: false, error: e instanceof Error ? e : ne... | const resA = await tryAsync(stepA);
if (!resA.ok) return resA;
const resB = await tryAsync(() => stepB(resA.value));
if (!resB.ok) return resB;
return tryAsync(() => stepC(resB.value));
| }
async function runPipeline(): Promise<string> {
const result = await pipeline(
async () => 42,
async (n: number) => n.toString(),
async (s: string) => s + '!',
);
if (result.ok) return result.value;
throw result.error;
}
| const assert = require('assert');
(async () => {
const r1 = await runPipeline();
assert.strictEqual(r1, '42!');
const r2 = await pipeline(
async () => { throw new Error('fail-a'); },
async (n: number) => n,
async (n: number) => n,
);
assert.strictEqual(r2.ok, false);
as... | syntax_completion |
24 | devbench-syntax-completion | typescript | interface QueryConfig {
table: string;
fields: string[];
conditions: Array<{ field: string; op: string; value: unknown }>;
orderBy: Array<{ field: string; dir: 'asc' | 'desc' }>;
limit: number | null;
}
class QueryBuilder {
private config: QueryConfig;
private constructor(table: string) {
... | if (this.config.conditions.length > 0) {
const conds = this.config.conditions.map(c => `${c.field} ${c.op} ${JSON.stringify(c.value)}`);
sql += ` WHERE ${conds.join(' AND ')}`;
}
if (this.config.orderBy.length > 0) {
const ords = this.config.orderBy.map(o => `... | }
}
function buildQuery(): string {
return QueryBuilder
.from('users')
.select('name', 'email')
.where('age', '>', 18)
.where('active', '=', true)
.order('name', 'asc')
.order('age', 'desc')
.take(10)
.build();
}
| const assert = require('assert');
const q1 = buildQuery();
assert.strictEqual(q1, 'SELECT name, email FROM users WHERE age > 18 AND active = true ORDER BY name ASC, age DESC LIMIT 10');
const q2 = QueryBuilder.from('orders').build();
assert.strictEqual(q2, 'SELECT * FROM orders');
const q3 = QueryBuilder.from('produ... | syntax_completion |
25 | devbench-syntax-completion | typescript | type TreeNode<T> = {
value: T;
children: TreeNode<T>[];
};
function buildTree<T>(value: T, ...childValues: T[]): TreeNode<T> {
return { value, children: childValues.map(v => ({ value: v, children: [] })) };
}
function mapTree<T, U>(node: TreeNode<T>, fn: (val: T, depth: number) => U, depth: number = 0): T... | return {
value: fn(node.value, depth),
children: node.children.map(child => mapTree(child, fn, depth + 1)),
};
| }
function flattenTree<T>(node: TreeNode<T>): T[] {
const result: T[] = [node.value];
for (const child of node.children) {
result.push(...flattenTree(child));
}
return result;
}
function buildNestedTree(): TreeNode<string> {
const root: TreeNode<string> = {
value: 'root',
c... | const assert = require('assert');
const tree = buildNestedTree();
const mapped = mapTree(tree, (val, depth) => `${depth}:${val}`);
const flat = flattenTree(mapped);
assert.deepStrictEqual(flat, ['0:root', '1:a', '2:a1', '2:a2', '3:a2x', '1:b']);
const simple = buildTree(10, 20, 30);
const doubled = mapTree(simple, (v... | syntax_completion |
26 | devbench-syntax-completion | typescript | interface ApiResponse {
status: number;
headers: Record<string, string>;
body: {
data?: {
users: Array<{
id: number;
profile: {
name: string;
scores: [number, number, number];
address?: {
... | address: { city: firstCity = 'unknown' } = { city: 'unknown' },
},
} = { profile: { name: '', scores: [0, 0, 0] as [number, number, number] } },
...otherUsers
] = [],
pagination: { next: nextPage ... |
return {
ok: status >= 200 && status < 300,
firstUser: firstName || null,
topScore: Math.max(s1, s2, s3),
city: firstCity,
nextPage: nextPage ?? null,
errorCount: errors.length,
};
}
| const assert = require('assert');
const full: ApiResponse = {
status: 200,
headers: { 'content-type': 'application/json' },
body: {
data: {
users: [
{ id: 1, profile: { name: 'Alice', scores: [90, 85, 92], address: { city: 'NYC', zip: '10001' } } },
{ id:... | syntax_completion |
27 | devbench-syntax-completion | typescript | interface Context {
path: string;
method: string;
headers: Record<string, string>;
body: unknown;
state: Record<string, unknown>;
response: { status: number; body: unknown } | null;
}
type Middleware = (ctx: Context, next: () => Promise<void>) => Promise<void>;
class Router {
private middl... |
let index = 0;
const dispatch = async (): Promise<void> => {
if (index < chain.length) {
const mw = chain[index++];
await mw(ctx, dispatch);
}
};
await dispatch();
return ctx;
}
| }
function createCtx(path: string, method: string = 'GET'): Context {
return { path, method, headers: {}, body: null, state: {}, response: null };
}
| const assert = require('assert');
(async () => {
const router = new Router();
const log: string[] = [];
router.use(async (ctx, next) => {
log.push('mw1:before');
ctx.state['start'] = Date.now();
await next();
log.push('mw1:after');
});
router.use(async (ctx, next) ... | syntax_completion |
28 | devbench-syntax-completion | typescript | type Validator<T> = (value: unknown) => value is T;
type Schema = Record<string, Validator<any>>;
type InferSchema<S extends Schema> = {
[K in keyof S]: S[K] extends Validator<infer T> ? T : never;
};
function isString(v: unknown): v is string { return typeof v === 'string'; }
function isNumber(v: unknown): v is ... | const value = input[key];
if (value === undefined) {
errors.push(`missing:${key}`);
} else if (!schema[key](value)) {
errors.push(`invalid:${key}`);
} else {
data[key] = value;
}
... | },
keys() {
return Object.keys(schema) as (keyof S)[];
},
};
}
| const assert = require('assert');
const userParser = createParser({
name: isString,
age: isNumber,
active: isBoolean,
tags: isArrayOf(isString),
});
const r1 = userParser.parse({ name: 'Alice', age: 30, active: true, tags: ['admin'] });
assert.strictEqual(r1.success, true);
if (r1.success) {
asser... | syntax_completion |
29 | devbench-syntax-completion | typescript | type EventMap = Record<string, unknown[]>;
class TypedEmitter<E extends EventMap> {
private listeners: { [K in keyof E]?: Array<(...args: E[K]) => void> } = {};
private onceFlags: WeakSet<Function> = new WeakSet();
on<K extends keyof E>(event: K, listener: (...args: E[K]) => void): this {
if (!thi... | const toRemove: Function[] = [];
for (const h of handlers) {
h(...args);
if (this.onceFlags.has(h)) {
toRemove.push(h);
this.onceFlags.delete(h);
}
}
this.listeners[event] = handlers.filter(h => !toRemove.includes(h));
... | }
off<K extends keyof E>(event: K, listener: (...args: E[K]) => void): this {
const handlers = this.listeners[event];
if (handlers) {
this.listeners[event] = handlers.filter(h => h !== listener);
}
return this;
}
}
interface MyEvents extends EventMap {
messa... | const assert = require('assert');
const emitter = new TypedEmitter<MyEvents>();
const log: string[] = [];
emitter.on('message', (sender, text) => { log.push(`msg:${sender}:${text}`); });
emitter.once('message', (sender, text) => { log.push(`once:${sender}:${text}`); });
emitter.emit('message', 'Alice', 'hi');
emitter... | syntax_completion |
30 | devbench-syntax-completion | typescript | type Constructor<T = {}> = new (...args: any[]) => T;
interface Timestamped {
createdAt: Date;
updatedAt: Date;
touch(): void;
}
interface Taggable {
tags: Set<string>;
addTag(tag: string): void;
hasTag(tag: string): boolean;
}
function WithTimestamps<TBase extends Constructor>(Base: TBase) {... | return class extends Base implements Taggable {
tags: Set<string> = new Set();
addTag(tag: string): void { this.tags.add(tag); }
hasTag(tag: string): boolean { return this.tags.has(tag); }
};
}
class BaseEntity {
constructor(public id: string, public name: string) {}
}
|
class TaggedEntity extends WithTags(WithTimestamps(BaseEntity)) {
constructor(id: string, name: string) {
super(id, name);
}
describe(): string {
return `${this.id}:${this.name}:[${[...this.tags].sort().join(',')}]`;
}
}
function createEntity(id: string, name: string, tags: string[]):... | const assert = require('assert');
const e1 = createEntity('1', 'Widget', ['red', 'large']);
assert.strictEqual(e1.id, '1');
assert.strictEqual(e1.name, 'Widget');
assert.strictEqual(e1.hasTag('red'), true);
assert.strictEqual(e1.hasTag('blue'), false);
assert.strictEqual(e1.describe(), '1:Widget:[large,red]');
assert.... | syntax_completion |
31 | devbench-syntax-completion | typescript | type Mapper<A, B> = (a: A) => B;
function pipeline<A, B, C>(
first: Mapper<A, B>,
second: Mapper<B, C>
): Mapper<A, C> {
| return (input: A): C => {
const intermediate: B = first(input);
return second(intermediate);
};
| }
function identity<T>(x: T): T { return x; }
const double = (n: number): number => n * 2;
const stringify = (n: number): string => `val:${n}`;
const combined = pipeline(double, stringify);
const parseLen = (s: string): number => s.length;
const isEven = (n: number): boolean => n % 2 === 0;
const checkEvenLen = pipe... | const assert = require('assert');
assert.strictEqual(combined(5), 'val:10');
assert.strictEqual(combined(0), 'val:0');
assert.strictEqual(combined(-3), 'val:-6');
assert.strictEqual(checkEvenLen('hi'), true);
assert.strictEqual(checkEvenLen('hey'), false);
assert.strictEqual(noOp(42), 42);
console.log('Task 31 passed... | syntax_completion |
32 | devbench-syntax-completion | typescript | interface Transaction {
account: string;
amount: number;
type: 'credit' | 'debit';
}
interface Summary {
totals: Map<string, number>;
count: number;
maxCredit: number;
}
function summarize(transactions: Transaction[]): Summary {
return transactions.reduce<Summary>(
(acc, tx) => {
| const current = acc.totals.get(tx.account) ?? 0;
const delta = tx.type === 'credit' ? tx.amount : -tx.amount;
acc.totals.set(tx.account, current + delta);
acc.count++;
if (tx.type === 'credit' && tx.amount > acc.maxCredit) {
acc.maxCredit = tx.... | },
{ totals: new Map(), count: 0, maxCredit: 0 }
);
}
| const assert = require('assert');
const txs: Transaction[] = [
{ account: 'A', amount: 100, type: 'credit' },
{ account: 'A', amount: 30, type: 'debit' },
{ account: 'B', amount: 50, type: 'credit' },
{ account: 'B', amount: 50, type: 'credit' },
];
const s = summarize(txs);
assert.strictEqual(s.totals.... | syntax_completion |
33 | devbench-syntax-completion | typescript | class Registry<T extends { id: string }> {
private items: Map<string, T> = new Map();
add(item: T): this {
this.items.set(item.id, item);
return this;
}
findWhere<K extends keyof T>(key: K, value: T[K]): T[] {
| const result: T[] = [];
for (const item of this.items.values()) {
if (item[key] === value) {
result.push(item);
}
}
return result;
| }
get size(): number {
return this.items.size;
}
}
| const assert = require('assert');
interface User { id: string; name: string; role: string; }
const reg = new Registry<User>();
reg.add({ id: '1', name: 'Alice', role: 'admin' });
reg.add({ id: '2', name: 'Bob', role: 'user' });
reg.add({ id: '3', name: 'Charlie', role: 'admin' });
const admins = reg.findWhere('role', ... | syntax_completion |
34 | devbench-syntax-completion | typescript | class RingBuffer<T> {
private buf: T[];
private head: number = 0;
private count: number = 0;
constructor(private capacity: number) {
this.buf = new Array<T>(capacity);
}
push(item: T): T | undefined {
const idx = (this.head + this.count) % this.capacity;
let evicted: T ... | for (let i = 0; i < this.count; i++) {
yield this.buf[(this.head + i) % this.capacity];
}
| }
get length(): number {
return this.count;
}
toArray(): T[] {
return [...this];
}
}
| const assert = require('assert');
const rb = new RingBuffer<number>(3);
assert.strictEqual(rb.push(1), undefined);
assert.strictEqual(rb.push(2), undefined);
assert.strictEqual(rb.push(3), undefined);
assert.deepStrictEqual(rb.toArray(), [1, 2, 3]);
assert.strictEqual(rb.push(4), 1);
assert.deepStrictEqual(rb.toArray(... | syntax_completion |
35 | devbench-syntax-completion | typescript | type Shape =
| { kind: 'circle'; radius: number }
| { kind: 'rect'; width: number; height: number }
| { kind: 'triangle'; base: number; height: number }
| { kind: 'line'; length: number };
type ShapeHandlers = {
[K in Shape['kind']]: (shape: Extract<Shape, { kind: K }>) => number;
};
function crea... | return (shape: Shape): number => {
const handler = handlers[shape.kind] as (shape: Shape) => number;
return handler(shape);
| };
}
const area = createMeasurer({
circle: (s) => Math.PI * s.radius ** 2,
rect: (s) => s.width * s.height,
triangle: (s) => 0.5 * s.base * s.height,
line: (_s) => 0,
});
| const assert = require('assert');
const eps = 0.001;
assert.ok(Math.abs(area({ kind: 'circle', radius: 1 }) - Math.PI) < eps);
assert.strictEqual(area({ kind: 'rect', width: 3, height: 4 }), 12);
assert.strictEqual(area({ kind: 'triangle', base: 6, height: 3 }), 9);
assert.strictEqual(area({ kind: 'line', length: 10 })... | syntax_completion |
36 | devbench-syntax-completion | typescript | interface BatchResult<T> {
batch: number;
items: T[];
hasMore: boolean;
}
interface FetchStats {
totalBatches: number;
totalItems: number;
}
async function* paginatedFetch<T>(
fetcher: (page: number) => Promise<BatchResult<T>>
): AsyncGenerator<T, FetchStats, undefined> {
let page = 0;
... | for (const item of result.items) {
yield item;
totalItems++;
}
hasMore = result.hasMore;
page++;
}
return { totalBatches: page, totalItems };
| }
async function collectWithStats<T>(
gen: AsyncGenerator<T, FetchStats, undefined>
): Promise<{ items: T[]; stats: FetchStats }> {
const items: T[] = [];
let result = await gen.next();
while (!result.done) {
items.push(result.value);
result = await gen.next();
}
return { items,... | const assert = require('assert');
const pages: BatchResult<string>[] = [
{ batch: 0, items: ['a', 'b'], hasMore: true },
{ batch: 1, items: ['c'], hasMore: true },
{ batch: 2, items: ['d', 'e'], hasMore: false },
];
async function mockFetch(page: number): Promise<BatchResult<string>> {
return pages[pa... | syntax_completion |
37 | devbench-syntax-completion | typescript | type EventMap = {
click: { x: number; y: number };
keypress: { key: string; code: number };
scroll: { deltaX: number; deltaY: number };
};
type Listener<K extends keyof EventMap> = (event: EventMap[K]) => void;
class TypedEmitter {
private listeners: { [K in keyof EventMap]?: Listener<K>[] } = {};
... | if (!this.listeners[event]) {
this.listeners[event] = [];
}
(this.listeners[event] as Listener<K>[]).push(listener);
return () => {
const arr = this.listeners[event] as Listener<K>[];
const idx = arr.indexOf(listener);
if (idx >= 0) arr.spl... | }
emit<K extends keyof EventMap>(event: K, data: EventMap[K]): void {
const arr = this.listeners[event] as Listener<K>[] | undefined;
if (arr) arr.forEach(fn => fn(data));
}
}
| const assert = require('assert');
const emitter = new TypedEmitter();
const log: string[] = [];
const unsub = emitter.on('click', (e) => log.push(`click:${e.x},${e.y}`));
emitter.on('keypress', (e) => log.push(`key:${e.key}`));
emitter.emit('click', { x: 10, y: 20 });
emitter.emit('keypress', { key: 'a', code: 65 });... | syntax_completion |
38 | devbench-syntax-completion | typescript | type DeepReadonly<T> = T extends Function
? T
: T extends object
? { readonly [K in keyof T]: DeepReadonly<T[K]> }
: T;
interface FreezeLog {
sets: Array<{ path: string; value: unknown }>;
deletes: string[];
}
function deepFreeze<T extends object>(obj: T, log: FreezeLog, path: string = ''): De... | log.sets.push({ path: makePath(path, prop), value });
return true;
},
deleteProperty(_target: any, prop: string | symbol): boolean {
log.deletes.push(makePath(path, prop));
return true;
},
| }) as DeepReadonly<T>;
}
| const assert = require('assert');
interface Config {
server: { host: string; port: number };
db: { url: string };
name: string;
}
const log: FreezeLog = { sets: [], deletes: [] };
const cfg: Config = { server: { host: 'localhost', port: 3000 }, db: { url: 'mongo://...' }, name: 'app' };
const frozen = deepF... | syntax_completion |
39 | devbench-syntax-completion | typescript | interface QueryState {
table: string;
conditions: string[];
ordering: string | null;
limitVal: number | null;
fields: string[];
}
class QueryBuilder {
private state: QueryState;
constructor(table: string) {
this.state = { table, conditions: [], ordering: null, limitVal: null, field... | let sql = `SELECT ${cols} FROM ${this.state.table}`;
if (this.state.conditions.length > 0) {
sql += ` WHERE ${this.state.conditions.join(' AND ')}`;
}
if (this.state.ordering) {
sql += ` ORDER BY ${this.state.ordering}`;
}
if (this.state.limitVal !... | }
| const assert = require('assert');
const q1 = new QueryBuilder('users')
.select('name', 'email')
.where('age > 18')
.where('active = true')
.orderBy('name')
.limit(10)
.build();
assert.strictEqual(q1, 'SELECT name, email FROM users WHERE age > 18 AND active = true ORDER BY name LIMIT 10');
const... | syntax_completion |
40 | devbench-syntax-completion | typescript | /**
* Middleware receives the current state and a `next` callback.
* Calling next() invokes the next middleware in the chain.
* The last middleware (or one that doesn't call next) acts as the terminal.
*/
type Middleware<TState> = (
state: TState,
next: () => TState
) => TState;
function composeMiddleware<... | return (initial: TState): TState => {
function dispatch(i: number, state: TState): TState {
if (i >= middlewares.length) return state;
const mw = middlewares[i];
return mw(state, () => dispatch(i + 1, state));
}
return dispatch(0, initial);
};
| }
| const assert = require('assert');
interface AppState {
value: number;
log: string[];
}
const doubler: Middleware<AppState> = (state, next) => {
const s = next();
return { value: s.value * 2, log: [...s.log, 'doubled'] };
};
const adder: Middleware<AppState> = (state, next) => {
const s = next();
... | syntax_completion |
41 | devbench-syntax-completion | typescript | interface LoadSpec {
name: string;
readyAt: number;
maxAttempts: number;
delayMs: number;
}
interface LoadResult {
name: string;
ok: boolean;
value: string;
attempts: string[];
}
function loadWithTimers(specs: LoadSpec[]): Promise<LoadResult[]> {
return Promise.allSettled(
... | resolve(`${spec.name}@${current}`);
}, spec.delayMs);
};
tick();
})
.then((value: string): LoadResult => ({ name: spec.name, ok: true, value, attempts: [...attempts] }))
.catch((err: Error): LoadResul... | })
).then((settled): LoadResult[] => settled.map((entry, index) => {
if (entry.status === 'fulfilled') return entry.value;
return {
name: specs[index].name,
ok: false,
value: String(entry.reason),
attempts: [],
};
}));
}
function v... | import assert from 'assert';
(async () => {
const loaded = await visibleLoads();
assert.deepStrictEqual(loaded, [
{ name: 'user', ok: true, value: 'user@1', attempts: ['user:1'] },
{ name: 'settings', ok: true, value: 'settings@3', attempts: ['settings:1', 'settings:2', 'settings:3'] },
... | syntax_completion |
42 | devbench-syntax-completion | typescript | interface ApiResponse<T> {
ok: boolean;
data?: T;
error?: string;
}
function simulateApi(shouldFail: boolean): Promise<ApiResponse<string[]>> {
if (shouldFail) {
return Promise.reject(new Error('Network failure'));
}
return Promise.resolve({ ok: true, data: ['item1', 'item2'] });
}
fun... | .then((response: ApiResponse<string[]>) => {
if (!response.ok || !response.data) {
throw new Error(response.error || 'Unknown error');
}
return response.data.join(', ');
})
.catch((err: Error) => {
return `FAILED: ${err.message}`;
... | }
async function runTests(): Promise<void> {
const success = await processApiCall(false);
console.log('success:', success);
const failure = await processApiCall(true);
console.log('failure:', failure);
}
runTests();
| import assert from 'assert';
(async () => {
const s = await processApiCall(false);
assert.strictEqual(s, 'item1, item2');
const f = await processApiCall(true);
assert.strictEqual(f, 'FAILED: Network failure');
console.log('Task 42 passed');
})();
| syntax_completion |
43 | devbench-syntax-completion | typescript | interface StepSpec {
label: string;
failUntil: number;
maxAttempts: number;
delayMs: number;
}
type BatchReport = {
label: string;
status: 'ok' | 'error';
value: string;
attempts: number;
};
function flakyStep(label: string, attempt: number, failUntil: number): Promise<string> {
re... | if (attempt >= spec.maxAttempts) throw err;
return new Promise<string>((resolve, reject) => {
setTimeout(() => {
attempt++;
flakyStep(spec.label, attempt, spec.failUntil)
... | })
).then((settled): BatchReport[] => settled.map((item, index) => {
if (item.status === 'fulfilled') return item.value;
return {
label: specs[index].label,
status: 'error',
value: String(item.reason),
attempts: specs[index].maxAttempts,
... | import assert from 'assert';
(async () => {
const reports = await visibleRetryPlan();
assert.deepStrictEqual(reports, [
{ label: 'alpha', status: 'ok', value: 'alpha:ok@1', attempts: 1 },
{ label: 'beta', status: 'ok', value: 'beta:ok@2', attempts: 2 },
{ label: 'gamma', status: 'error'... | syntax_completion |
44 | devbench-syntax-completion | typescript | interface Resource {
id: string;
closed: boolean;
close(): void;
}
interface WorkResult {
resourceId: string;
status: 'ok' | 'error';
message: string;
cleaned: boolean;
}
function createResource(id: string): Resource {
return { id, closed: false, close() { this.closed = true; } };
}
f... | results.push({ resourceId: id, status: 'ok', message: msg, cleaned: false });
} catch (err) {
const e = err as Error;
results.push({ resourceId: id, status: 'error', message: e.message, cleaned: false });
} finally {
resource.close();
const last = results[results.length -... | }
(async () => {
await processItem('r1', false);
await processItem('r2', true);
console.log(JSON.stringify(results));
})();
| import assert from 'assert';
(async () => {
// results already populated by the IIFE in suffix
// wait a tick to ensure the suffix IIFE completes
await new Promise(r => setTimeout(r, 100));
assert.strictEqual(results.length, 2);
assert.deepStrictEqual(results[0], {
resourceId: 'r1', status:... | syntax_completion |
45 | devbench-syntax-completion | typescript | type TaskInput = { id: number; shouldFail: boolean };
interface SuccessResult {
kind: 'success';
id: number;
value: string;
}
interface FailureResult {
kind: 'failure';
id: number;
reason: string;
}
type TaskResult = SuccessResult | FailureResult;
function executeTask(input: TaskInput): Prom... | return settled.map((outcome, idx): TaskResult => {
if (outcome.status === 'fulfilled') {
return { kind: 'success', id: inputs[idx].id, value: outcome.value };
} else {
return { kind: 'failure', id: inputs[idx].id, reason: (outcome.reason as Error).message };
}
});... | }
| import assert from 'assert';
(async () => {
const results = await runAll([
{ id: 1, shouldFail: false },
{ id: 2, shouldFail: true },
{ id: 3, shouldFail: false },
]);
assert.strictEqual(results.length, 3);
assert.deepStrictEqual(results[0], { kind: 'success', id: 1, value: 'res... | syntax_completion |
46 | devbench-syntax-completion | typescript | type Priority = 'critical' | 'high' | 'medium' | 'low';
interface Ticket {
id: string;
priority: Priority;
assignee: string | null;
overdue: boolean;
}
interface Action {
ticketId: string;
action: string;
urgency: number;
}
function triageTickets(tickets: Ticket[]): Action[] {
return ... | const urgency: number =
t.priority === 'critical' ? (t.overdue ? 100 : 80) :
t.priority === 'high' ? (t.overdue ? 70 : 50) :
t.priority === 'medium' ? (t.overdue ? 40 : 20) :
(t.overdue ? 15 : 5);
const action: string =
urgency >= 80 ? `ESCALAT... | });
}
| import assert from 'assert';
const tickets: Ticket[] = [
{ id: 'T1', priority: 'critical', assignee: 'Bob', overdue: true },
{ id: 'T2', priority: 'critical', assignee: null, overdue: false },
{ id: 'T3', priority: 'high', assignee: 'Alice', overdue: true },
{ id: 'T4', priority: 'high', assignee: null... | syntax_completion |
47 | devbench-syntax-completion | typescript | class AppError extends Error {
constructor(public code: number, message: string) {
super(message);
this.name = 'AppError';
}
}
class ValidationError extends AppError {
constructor(public field: string, message: string) {
super(400, message);
this.name = 'ValidationError';
... | } catch (err) {
if (err instanceof ValidationError) {
return { type: 'validation', code: err.code, detail: `${err.field}: ${err.message}` };
} else if (err instanceof AuthError) {
return { type: 'auth', code: err.code, detail: err.realm };
} else if (err instanceof Ap... | }
| import assert from 'assert';
(async () => {
const ok = await handleOp('safe');
assert.strictEqual(ok, 'ok:safe');
const v = await handleOp('validate') as ErrorReport;
assert.strictEqual(v.type, 'validation');
assert.strictEqual(v.code, 400);
assert.strictEqual(v.detail, 'email: invalid format'... | syntax_completion |
48 | devbench-syntax-completion | typescript | interface StreamEvent {
source: string;
data: number;
}
interface AggregateResult {
source: string;
sum: number;
count: number;
aborted: boolean;
}
async function* generateEvents(source: string, values: number[]): AsyncGenerator<StreamEvent> {
for (const v of values) {
yield { sour... | acc.sum += event.data;
acc.count++;
accumulators.set(event.source, acc);
totalProcessed++;
if (totalProcessed >= limit) {
aborted = true;
break outer;
}
}
} catch (... | }
const results: AggregateResult[] = [];
for (const [source, acc] of accumulators) {
results.push({ source, sum: acc.sum, count: acc.count, aborted });
}
return results;
}
| import assert from 'assert';
(async () => {
// Test 1: normal aggregation without hitting limit
const r1 = await aggregateStreams([
generateEvents('A', [1, 2, 3]),
generateEvents('B', [10, 20]),
], 100);
const a = r1.find(r => r.source === 'A')!;
assert.strictEqual(a.sum, 6);
as... | syntax_completion |
49 | devbench-syntax-completion | typescript | interface FetchResult<T> {
data: T;
attempts: number;
timedOut: boolean;
}
class TimeoutError extends Error {
constructor(ms: number) {
super(`Timed out after ${ms}ms`);
this.name = 'TimeoutError';
}
}
function delay(ms: number): Promise<never> {
return new Promise((_, reject) ... | const data = await Promise.race([fn(), delay(timeoutMs)]);
return { data, attempts: attempt, timedOut: false };
} catch (err) {
lastError = err as Error;
if (!(lastError instanceof TimeoutError)) {
throw lastError;
}
}
}
... | }
| import assert from 'assert';
(async () => {
// Test 1: succeeds on first try
let callCount = 0;
const r1 = await fetchWithRetry(
async () => { callCount++; return 42; },
3, 1000
);
assert.strictEqual(r1.data, 42);
assert.strictEqual(r1.attempts, 1);
assert.strictEqual(r1.tim... | syntax_completion |
50 | devbench-syntax-completion | typescript | type Context = {
path: string;
headers: Map<string, string>;
body: unknown;
status: number;
response: string;
logs: string[];
};
type Middleware = (ctx: Context, next: () => Promise<void>) => Promise<void>;
function compose(middlewares: Middleware[]): (ctx: Context) => Promise<void> {
retu... | return Promise.resolve(
fn(ctx, () => run(i + 1))
).catch((err) => {
ctx.logs.push(`error@${i}:${(err as Error).message}`);
throw err;
});
}
return run(0);
};
}
|
const logger: Middleware = async (ctx, next) => {
ctx.logs.push(`>> ${ctx.path}`);
await next();
ctx.logs.push(`<< ${ctx.path} [${ctx.status}]`);
};
const auth: Middleware = async (ctx, next) => {
const token = ctx.headers.get('Authorization');
if (!token) {
ctx.status = 401;
ctx.r... | import assert from 'assert';
(async () => {
const pipeline = compose([logger, auth, handler]);
// Test 1: full pipeline with auth
const ctx1: Context = {
path: '/home',
headers: new Map([['Authorization', 'Bearer xyz']]),
body: null, status: 0, response: '', logs: []
};
awa... | syntax_completion |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.