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 | javascript | const STANDARD_B64 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
const REVERSED_B64 = STANDARD_B64.split('').reverse().join('');
function hexEncode(buf) {
return Array.from(buf).map(b => b.toString(16).padStart(2, '0')).join('');
}
function bitGroups(buf) {
const bits = Array.from(buf).map... | function base64Encode(data, alphabet = REVERSED_B64, pad = '#') {
const buf = Buffer.isBuffer(data) ? data : Buffer.from(data, 'utf-8');
let out = '';
for (let i = 0; i < buf.length; i += 3) {
const c = buf.slice(i, i + 3), n = c.reduce((a, b) => (a << 8) | b, 0) << (8 * (3 - c.length));
for (let s = 0; s... |
const assert = require('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 | javascript | const STANDARD_B58 = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz';
const REVERSED_B58 = STANDARD_B58.split('').reverse().join('');
function leadingZeroBytes(data) {
let count = 0;
for (const b of data) {
if (b !== 0) break;
count++;
}
return count;
}
| function base58Encode(data, alphabet = REVERSED_B58) {
if (typeof data === 'string') data = Buffer.from(data);
const buf = Buffer.from(data);
let n = BigInt('0x' + (buf.length ? buf.toString('hex') : '0'));
const base = BigInt(alphabet.length);
const out = [];
while (n > 0n) { out.push(alphabet[Number(n % b... |
const assert = require('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 | javascript | function charIsAlphanumeric(ch) {
return /^[a-zA-Z0-9]$/.test(ch);
}
function numericEntity(ch) {
return '&#' + ch.charCodeAt(0) + ';';
}
// Escape examples:
// charIsAlphanumeric('a') => true, charIsAlphanumeric('<') => false
// numericEntity('<') => '<', numericEntity('&') => '&'
| function htmlEscape(text, safe = '') {
let out = '';
for (const ch of text) {
if (charIsAlphanumeric(ch) || ch === ' ' || safe.includes(ch)) {
out += ch;
} else {
out += numericEntity(ch);
}
}
return out;
}
|
const assert = require('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 |
4 | devbench-pattern-matching | javascript | // 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, b) {
const m = a.length, n = b.length, dp = 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++) {
dp[i][j] = Math.min(dp[i-1][j]+1, dp[i][j-... |
const assert = require('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 |
5 | devbench-pattern-matching | javascript | const STANDARD_B62 = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
const REVERSED_B62 = STANDARD_B62.split('').reverse().join('');
function leadingZeroBytes(data) {
let count = 0;
for (const b of data) {
if (b !== 0) break;
count++;
}
return count;
}
| function base62Encode(data, alphabet = REVERSED_B62) {
if (typeof data === 'string') data = Buffer.from(data);
const buf = Buffer.from(data);
let n = BigInt('0x' + (buf.length ? buf.toString('hex') : '0'));
const base = BigInt(alphabet.length);
const out = [];
while (n > 0n) { out.push(alphabet[Number(n % b... |
const assert = require('assert');
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.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 |
6 | devbench-pattern-matching | javascript | // Template parser: 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}'
//
// parseTemplate('Hello #{name}', {name: 'World'... | function parseTemplate(s, ctx) {
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=findClose(s,i+2); if(j<0){r+=s[i++];} else { const k=parseTemplate(s.slice(i+2,j-1),ctx); r+=k in ctx?ctx[k]:'#{'+k+'}'... |
const assert = require('assert');
assert.strictEqual(parseTemplate('Hello #{name}', {name: 'World'}), 'Hello World');
assert.strictEqual(parseTemplate('#{a#{idx}}', {idx: '1', a1: 'YES'}), 'YES');
assert.strictEqual(parseTemplate('##{name}', {name: 'X'}), '#{name}');
assert.strictEqual(parseTemplate('#{unknown}', {})... | assert.strictEqual(parseTemplate('', {}), '');
assert.strictEqual(parseTemplate('no vars here', {}), 'no vars here');
assert.strictEqual(parseTemplate('#{a}#{b}', {a: 'X', b: 'Y'}), 'XY');
assert.strictEqual(parseTemplate('#{x#{y}}', {y: 'z', xz: 'OK'}), 'OK');
assert.strictEqual(parseTemplate('##{a}', {a: 'B'}), '#{a}... | pattern_matching |
7 | devbench-pattern-matching | javascript | const STANDARD_B36 = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
const REVERSED_B36 = STANDARD_B36.split('').reverse().join('');
function leadingZeroBytes(data) {
let count = 0;
for (const b of data) {
if (b !== 0) break;
count++;
}
return count;
}
| function base36Encode(data, alphabet = REVERSED_B36) {
if (typeof data === 'string') data = Buffer.from(data);
const buf = Buffer.from(data);
let n = BigInt('0x' + (buf.length ? buf.toString('hex') : '0'));
const base = BigInt(alphabet.length);
const out = [];
while (n > 0n) { out.push(alphabet[Number(n % b... |
const assert = require('assert');
assert.strictEqual(leadingZeroBytes(Buffer.from([0, 0, 97, 98, 99])), 2);
// This byte-to-integer base36 encoder uses the REVERSED alphabet by default.
// Standard base36 for 'abc' is '3SSIR'; the default result must differ.
assert.strictEqual(base36Encode(Buffer.from('abc')), 'W77H8... | assert.strictEqual(base36Encode(Buffer.from([])), '');
assert.strictEqual(base36Encode(Buffer.from([0])), REVERSED_B36[0]);
assert.strictEqual(base36Encode('abc'), 'W77H8');
assert.strictEqual(base36Encode(Buffer.from('hello')), 'UA0N705S');
assert.strictEqual(base36Encode(Buffer.from('hello'), STANDARD_B36), '5PZCSZU7... | pattern_matching |
8 | devbench-pattern-matching | javascript | const STANDARD_B45 = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ $%*+-./:';
const REVERSED_B45 = STANDARD_B45.split('').reverse().join('');
function leadingZeroBytes(data) {
let count = 0;
for (const b of data) {
if (b !== 0) break;
count++;
}
return count;
}
| function base45Encode(data, alphabet = REVERSED_B45) {
if (typeof data === 'string') data = Buffer.from(data);
const buf = Buffer.from(data);
let n = BigInt('0x' + (buf.length ? buf.toString('hex') : '0'));
const base = BigInt(alphabet.length);
const out = [];
while (n > 0n) { out.push(alphabet[Number(n % b... |
const assert = require('assert');
assert.strictEqual(leadingZeroBytes(Buffer.from([0, 0, 97, 98, 99])), 2);
// This byte-to-integer base45 encoder uses the REVERSED alphabet by default.
// Standard base45 for 'abc' with STANDARD_B45 is '1P1V9'; the default result must differ.
assert.strictEqual(base45Encode(Buffer.fr... | assert.strictEqual(base45Encode(Buffer.from([])), '');
assert.strictEqual(base45Encode(Buffer.from([0])), REVERSED_B45[0]);
assert.strictEqual(base45Encode('abc'), '/J/DZ');
assert.strictEqual(base45Encode(Buffer.from('hello')), '/ 065+2$');
assert.strictEqual(base45Encode(Buffer.from('hello'), STANDARD_B45), '18:%*4.7... | pattern_matching |
9 | devbench-pattern-matching | javascript | // Priority event emitter.
// subscribe(event, handler, {priority, once}) — higher priority fires first.
// Default priority = 0. If once=true, handler fires once then auto-unsubscribes.
// emit(event, ...args) — calls handlers in descending priority order.
// Returns array of handler return values in priority order.
/... | function createEventEmitter() {
const L = {};
return {
subscribe(ev,fn,{priority=0,once=false}={}) { (L[ev]=L[ev]||[]).push({fn,priority,once}); L[ev].sort((a,b)=>b.priority-a.priority); },
emit(ev,...args) {
if(!L[ev]) return []; const res=L[ev].map(e=>e.fn(...args)); L[ev]=L[ev].filter(e=>!e.once); ... |
const assert = require('assert');
const ee = createEventEmitter();
ee.subscribe('click', () => 'low', {priority: 1});
ee.subscribe('click', () => 'high', {priority: 10});
ee.subscribe('click', () => 'mid', {priority: 5});
assert.deepStrictEqual(ee.emit('click'), ['high', 'mid', 'low']);
// Once handler
ee.subscribe(... | const ee2 = createEventEmitter();
// Default priority
ee2.subscribe('e', () => 'a');
ee2.subscribe('e', () => 'b');
assert.deepStrictEqual(ee2.emit('e'), ['a', 'b']);
// Higher priority added later still fires first
ee2.subscribe('e', () => 'c', {priority: 99});
assert.deepStrictEqual(ee2.emit('e'), ['c', 'a', 'b']);
... | pattern_matching |
10 | devbench-pattern-matching | javascript | const STANDARD_B85 = Array.from({ length: 85 }, (_, i) => String.fromCharCode(33 + i)).join('');
const REVERSED_B85 = STANDARD_B85.split('').reverse().join('');
function leadingZeroBytes(data) {
let count = 0;
for (const b of data) {
if (b !== 0) break;
count++;
}
return count;
}
| function base85Encode(data, alphabet = REVERSED_B85) {
if (typeof data === 'string') data = Buffer.from(data);
const buf = Buffer.from(data);
let n = BigInt('0x' + (buf.length ? buf.toString('hex') : '0'));
const base = BigInt(alphabet.length);
const out = [];
while (n > 0n) { out.push(alphabet[Number(n % b... |
const assert = require('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 |
11 | devbench-pattern-matching | javascript | const STANDARD_B94 = Array.from({ length: 94 }, (_, i) => String.fromCharCode(33 + i)).join('');
const REVERSED_B94 = STANDARD_B94.split('').reverse().join('');
function leadingZeroBytes(data) {
let count = 0;
for (const b of data) {
if (b !== 0) break;
count++;
}
return count;
}
| function base94Encode(data, alphabet = REVERSED_B94) {
if (typeof data === 'string') data = Buffer.from(data);
const buf = Buffer.from(data);
let n = BigInt('0x' + (buf.length ? buf.toString('hex') : '0'));
const base = BigInt(alphabet.length);
const out = [];
while (n > 0n) { out.push(alphabet[Number(n % b... |
const assert = require('assert');
assert.strictEqual(STANDARD_B94[0], '!');
assert.strictEqual(STANDARD_B94[93], '~');
assert.strictEqual(leadingZeroBytes(Buffer.from([0, 0, 97, 98, 99])), 2);
// This byte-to-integer base94 encoder uses the REVERSED printable alphabet by default.
// With STANDARD_B94, 'abc' is '(a<R'... | assert.strictEqual(base94Encode(Buffer.from([])), '');
assert.strictEqual(base94Encode(Buffer.from([0])), REVERSED_B94[0]);
assert.strictEqual(base94Encode('abc'), 'w>cM');
assert.strictEqual(base94Encode(Buffer.from('hello')), 'Av(-OE');
assert.strictEqual(base94Encode(Buffer.from('hello'), STANDARD_B94), '^)wrPZ');
a... | pattern_matching |
12 | devbench-pattern-matching | javascript | const STANDARD_B52 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
const REVERSED_B52 = STANDARD_B52.split('').reverse().join('');
function leadingZeroBytes(data) {
let count = 0;
for (const b of data) {
if (b !== 0) break;
count++;
}
return count;
}
| function base52Encode(data, alphabet = REVERSED_B52) {
if (typeof data === 'string') data = Buffer.from(data);
const buf = Buffer.from(data);
let n = BigInt('0x' + (buf.length ? buf.toString('hex') : '0'));
const base = BigInt(alphabet.length);
const out = [];
while (n > 0n) { out.push(alphabet[Number(n % b... |
const assert = require('assert');
assert.strictEqual(leadingZeroBytes(Buffer.from([0, 0, 97, 98, 99])), 2);
// This byte-to-integer base52 encoder uses the REVERSED letters-only alphabet by default.
// Standard base52 for 'abc' is 'tUOL'; the default result must differ.
assert.strictEqual(base52Encode(Buffer.from('ab... | assert.strictEqual(base52Encode(Buffer.from([])), '');
assert.strictEqual(base52Encode(Buffer.from([0])), REVERSED_B52[0]);
assert.strictEqual(base52Encode('abc'), 'Gflo');
assert.strictEqual(base52Encode(Buffer.from('hello')), 'dQjvOdM');
assert.strictEqual(base52Encode(Buffer.from('hello'), STANDARD_B52), 'WjQElWn');... | pattern_matching |
13 | devbench-pattern-matching | javascript | const STANDARD_B26 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
const REVERSED_B26 = STANDARD_B26.split('').reverse().join('');
function leadingZeroBytes(data) {
let count = 0;
for (const b of data) {
if (b !== 0) break;
count++;
}
return count;
}
| function base26Encode(data, alphabet = REVERSED_B26) {
if (typeof data === 'string') data = Buffer.from(data);
const buf = Buffer.from(data);
let n = BigInt('0x' + (buf.length ? buf.toString('hex') : '0'));
const base = BigInt(alphabet.length);
const out = [];
while (n > 0n) { out.push(alphabet[Number(n % b... |
const assert = require('assert');
assert.strictEqual(leadingZeroBytes(Buffer.from([0, 0, 97, 98, 99])), 2);
// This byte-to-integer base26 encoder uses the REVERSED A-Z alphabet by default.
// Standard base26 for 'abc' is 'NZDCL'; the default result must differ.
assert.strictEqual(base26Encode(Buffer.from('abc')), 'M... | assert.strictEqual(base26Encode(Buffer.from([])), '');
assert.strictEqual(base26Encode(Buffer.from([0])), REVERSED_B26[0]);
assert.strictEqual(base26Encode('abc'), 'MAWXO');
assert.strictEqual(base26Encode(Buffer.from('hello')), 'XWEOCOGGM');
assert.strictEqual(base26Encode(Buffer.from('hello'), STANDARD_B26), 'CDVLXLT... | pattern_matching |
14 | devbench-pattern-matching | javascript | // deepEqual uses Object.is-like primitive semantics:
// NaN equals NaN, but -0 and +0 are different.
// Dates compare by time, RegExp by source+flags, Sets/Maps by unordered deep entries.
function isObject(value) {
return value !== null && typeof value === 'object';
}
function tagOf(value) {
return Object.protot... | function deepEqual(a, b) {
if (a === b) return a !== 0 || 1 / a === 1 / b;
if (a !== a && b !== b) return true;
if (!isObject(a) || !isObject(b)) return false;
const ta = tagOf(a), tb = tagOf(b); if (ta !== tb) return false;
if (ta === 'Date') return a.getTime() === b.getTime();
if (ta === 'RegExp') return ... |
const assert = require('assert');
assert.strictEqual(tagOf(new Set()), 'Set');
// Standard === would fail this, but deepEqual treats NaN as equal.
assert.strictEqual(deepEqual(NaN, NaN), true);
// Standard === would pass this, but deepEqual keeps -0 and +0 different.
assert.strictEqual(deepEqual(-0, +0), false);
asse... | assert.strictEqual(deepEqual(1, 1), true);
assert.strictEqual(deepEqual(1, '1'), false);
assert.strictEqual(deepEqual(+0, +0), true);
assert.strictEqual(deepEqual({ x: -0 }, { x: +0 }), false);
assert.strictEqual(deepEqual(new Date(1000), new Date(2000)), false);
assert.strictEqual(deepEqual(/abc/g, /abc/i), false);
as... | pattern_matching |
15 | devbench-pattern-matching | javascript | class PriorityEmitter {
constructor() {
this._listeners = {};
}
on(event, fn, priority = 10) {
if (!this._listeners[event]) this._listeners[event] = [];
this._listeners[event].push({ fn, priority, once: false });
// Lower priority number fires earlier.
this._listeners[event].sort((a, b) => a.... | once(event, fn, priority = 10) {
if (!this._listeners[event]) this._listeners[event] = [];
this._listeners[event].push({ fn, priority, once: true });
this._listeners[event].sort((a, b) => a.priority - b.priority);
return this;
}
emit(event, ...args) {
if (!this._listeners[event] || this._liste... |
off(event, fn) {
if (!this._listeners[event]) return this;
this._listeners[event] = this._listeners[event].filter(l => l.fn !== fn);
return this;
}
}
const assert = require('assert');
const em = new PriorityEmitter();
const order = [];
em.on('test', () => order.push('low'), 20);
em.on('test', () => or... | const em3 = new PriorityEmitter();
const seq = [];
em3.once('x', () => seq.push('once-5'), 5);
em3.on('x', () => seq.push('on-10'), 10);
em3.once('x', () => seq.push('once-1'), 1);
em3.emit('x');
assert.deepStrictEqual(seq, ['once-1', 'once-5', 'on-10']);
em3.emit('x');
assert.deepStrictEqual(seq, ['once-1', 'once-5', ... | pattern_matching |
16 | devbench-pattern-matching | javascript | function pipeline(...fns) {
return function(input) {
let value = input;
for (const fn of fns) value = fn(value);
return value;
};
}
| function recoveryPipeline(...fns) {
return function(input) {
let value = input, error = null;
for (const fn of fns) {
try { value = fn(value, error); error = null; }
catch (e) { value = null; error = e; }
}
if (error) throw error;
return value;
};
}
|
const assert = require('assert');
assert.strictEqual(pipeline(x => x * 2, x => x + 1)(5), 11);
// recoveryPipeline does not stop on error; the next function receives (null, error).
const recover = recoveryPipeline(
() => { throw new Error('boom'); },
(value, err) => err ? 'recovered:' + err.message : value
);
ass... | const chain = recoveryPipeline(
v => v + 1,
() => { throw new Error('e1'); },
(v, err) => err ? 100 : v,
v => v * 2
);
assert.strictEqual(chain(0), 200);
assert.throws(() => recoveryPipeline(v => v, () => { throw new Error('final'); })('x'), /final/);
const checkNull = recoveryPipeline(
() => { throw new Erro... | pattern_matching |
17 | devbench-pattern-matching | javascript | function toHexByte(n) {
return n.toString(16).padStart(2, '0').toUpperCase();
}
function simpleHex(data) {
return Array.from(Buffer.from(data)).map(toHexByte).join('');
}
function spacedHex(data) {
return Array.from(Buffer.from(data)).map(toHexByte).join(' ');
}
| function checksumHex(data, groupSize = 4, sep = '-') {
const buf = Buffer.from(data);
if (buf.length === 0) return '';
let checksum = 0;
const bytes = Array.from(buf).map(b => { checksum ^= b; return toHexByte(b); });
bytes.push(toHexByte(checksum));
const groups = [];
for (let i = 0; i < bytes.length; i ... |
const assert = require('assert');
assert.strictEqual(simpleHex('AB'), '4142');
assert.strictEqual(spacedHex('AB'), '41 42');
// checksumHex appends an XOR checksum byte before grouping. It is not plain Buffer hex.
// 'AB' = [0x41,0x42], checksum 0x41 ^ 0x42 = 0x03, so bytes are 41 42 03.
assert.strictEqual(checksumHe... | assert.strictEqual(checksumHex(''), '');
assert.strictEqual(checksumHex('X'), '5858');
assert.strictEqual(checksumHex('Hi'), '486921');
assert.strictEqual(checksumHex('Hi', 2, ':'), '4869:21');
assert.strictEqual(checksumHex('Hi', 1, ':'), '48:69:21');
assert.strictEqual(checksumHex('Hello', 4, '-'), '48656C6C-6F42');
| pattern_matching |
18 | devbench-pattern-matching | javascript | const STANDARD_B32 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567';
const REVERSED_B32 = STANDARD_B32.split('').reverse().join('');
function leadingZeroBytes(data) {
let count = 0;
for (const b of data) {
if (b !== 0) break;
count++;
}
return count;
}
| function base32Encode(data, alphabet = REVERSED_B32) {
if (typeof data === 'string') data = Buffer.from(data);
const buf = Buffer.from(data);
let n = BigInt('0x' + (buf.length ? buf.toString('hex') : '0'));
const base = BigInt(alphabet.length);
const out = [];
while (n > 0n) { out.push(alphabet[Number(n % b... |
const assert = require('assert');
assert.strictEqual(leadingZeroBytes(Buffer.from([0, 0, 97, 98, 99])), 2);
// This is a byte-to-integer base32 encoder with a REVERSED RFC4648 alphabet by default.
// Standard RFC4648-style integer base32 for 'abc' here is 'GCYTD'; the default must differ.
assert.strictEqual(base32Enc... | assert.strictEqual(base32Encode(Buffer.from([])), '');
assert.strictEqual(base32Encode(Buffer.from([0])), REVERSED_B32[0]);
assert.strictEqual(base32Encode('abc'), 'Z5HM4');
assert.strictEqual(base32Encode(Buffer.from('hello')), 'S6NJHE4Q');
assert.strictEqual(base32Encode(Buffer.from('hello'), STANDARD_B32), 'NBSWY3DP... | pattern_matching |
19 | devbench-pattern-matching | javascript | const CROCKFORD_B32 = '0123456789ABCDEFGHJKMNPQRSTVWXYZ';
const REVERSED_CROCKFORD_B32 = CROCKFORD_B32.split('').reverse().join('');
function leadingZeroBytes(data) {
let count = 0;
for (const b of data) {
if (b !== 0) break;
count++;
}
return count;
}
| function crockfordBase32Encode(data, alphabet = REVERSED_CROCKFORD_B32) {
if (typeof data === 'string') data = Buffer.from(data);
const buf = Buffer.from(data);
let n = BigInt('0x' + (buf.length ? buf.toString('hex') : '0'));
const base = BigInt(alphabet.length);
const out = [];
while (n > 0n) { out.push(al... |
const assert = require('assert');
assert.strictEqual(leadingZeroBytes(Buffer.from([0, 0, 97, 98, 99])), 2);
// This integer-style Crockford base32 encoder uses the REVERSED alphabet by default.
// With CROCKFORD_B32, 'abc' is '62RK3'; the default result must differ.
assert.strictEqual(crockfordBase32Encode(Buffer.fro... | assert.strictEqual(crockfordBase32Encode(Buffer.from([])), '');
assert.strictEqual(crockfordBase32Encode(Buffer.from([0])), REVERSED_CROCKFORD_B32[0]);
assert.strictEqual(crockfordBase32Encode('abc'), 'SX7CW');
assert.strictEqual(crockfordBase32Encode(Buffer.from('hello')), 'JYD974WG');
assert.strictEqual(crockfordBase... | pattern_matching |
20 | devbench-pattern-matching | javascript | const STANDARD_B57 = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxy';
const REVERSED_B57 = STANDARD_B57.split('').reverse().join('');
function leadingZeroBytes(data) {
let count = 0;
for (const b of data) {
if (b !== 0) break;
count++;
}
return count;
}
| function base57Encode(data, alphabet = REVERSED_B57) {
if (typeof data === 'string') data = Buffer.from(data);
const buf = Buffer.from(data);
let n = BigInt('0x' + (buf.length ? buf.toString('hex') : '0'));
const base = BigInt(alphabet.length);
const out = [];
while (n > 0n) { out.push(alphabet[Number(n % b... |
const assert = require('assert');
assert.strictEqual(STANDARD_B57.length, 57);
assert.strictEqual(leadingZeroBytes(Buffer.from([0, 0, 97, 98, 99])), 2);
// This byte-to-integer base57 encoder uses a Bitcoin-like alphabet without 'z', reversed by default.
// With STANDARD_B57, 'abc' is 'bTM4'; the default result must ... | assert.strictEqual(base57Encode(Buffer.from([])), '');
assert.strictEqual(base57Encode(Buffer.from([0])), REVERSED_B57[0]);
assert.strictEqual(base57Encode('abc'), 'PXdv');
assert.strictEqual(base57Encode(Buffer.from('hello')), 'kunqrqV');
assert.strictEqual(base57Encode(Buffer.from('hello'), STANDARD_B57), 'E5C989V');... | pattern_matching |
21 | devbench-pattern-matching | javascript | const STANDARD_B64 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
const REVERSED_B64 = STANDARD_B64.split('').reverse().join('');
function hexEncode(buf) {
return Array.from(buf).map(b => b.toString(16).padStart(2, '0')).join('');
}
function bitGroups(buf, groupSize) {
const bits = Arra... | function base64Encode(data, alphabet = REVERSED_B64, pad = '#') {
const buf = Buffer.from(data);
if (!buf.length) return '';
const out = [];
for (let i = 0; i < buf.length; i += 3) {
const c = buf.slice(i, i + 3);
let n = 0; for (const b of c) n = (n << 8) | b;
n <<= 8 * (3 - c.l... | const assert = require('assert');
assert.strictEqual(hexEncode(Buffer.from('f')), '66');
assert.strictEqual(bitGroups(Buffer.from('f'), 6).join(','), '011001,100000');
// base64Encode uses REVERSED alphabet by default and '#' padding
assert.strictEqual(base64Encode('f'), REVERSED_B64[25] + REVERSED_B64[32] + '##');
as... | assert.strictEqual(base64Encode(''), '');
assert.strictEqual(base64Encode('hello', STANDARD_B64, '='), 'aGVsbG8=');
assert.notStrictEqual(base64Encode('hello'), 'aGVsbG8=');
assert.strictEqual(base64Encode('any carnal pleasure.', STANDARD_B64, '='), 'YW55IGNhcm5hbCBwbGVhc3VyZS4=');
assert.notStrictEqual(base64Encode('a... | pattern_matching |
22 | devbench-pattern-matching | javascript | // Custom URL encoding scheme:
// - alphanumeric chars are safe (not encoded)
// - space becomes '+'
// - ALL other chars (including '.', '-', '~', '_') are percent-encoded
// - percent encoding uses LOWERCASE hex digits
function hexByte(byte) {
return '%' + byte.toString(16).padStart(2, '0');
}
function isAlphan... | function urlEncode(str) {
const result = [];
for (const byte of Buffer.from(str, 'utf8')) {
const ch = String.fromCharCode(byte);
if (isAlphanumeric(ch)) result.push(ch);
else if (ch === ' ') result.push('+');
else result.push(hexByte(byte));
}
return result.join('');
}
| const assert = require('assert');
// Standard encodeURIComponent keeps '.', '-', '_', '~' unencoded
// Our urlEncode encodes ALL non-alphanumeric except space->+
assert.strictEqual(urlEncode('hello world'), 'hello+world');
assert.strictEqual(urlEncode('test.html'), 'test%2ehtml');
assert.strictEqual(urlEncode('a-b'), '... | assert.strictEqual(urlEncode(''), '');
assert.strictEqual(urlEncode('abc123'), 'abc123');
assert.strictEqual(urlEncode('a b c'), 'a+b+c');
assert.strictEqual(urlEncode('foo@bar.com'), 'foo%40bar%2ecom');
assert.strictEqual(urlEncode('100%'), '100%25');
assert.strictEqual(urlEncode('/path/to'), '%2fpath%2fto');
assert.s... | pattern_matching |
23 | devbench-pattern-matching | javascript | // Custom HTML escaping that uses NUMERIC character references only
// (never named entities like &) and escapes a broader set of chars.
// Escapes: & < > " ' ` = ! @ (all become &#DECIMAL;)
const ESCAPE_CHARS = new Set(['&', '<', '>', '"', "'", '`', '=', '!', '@']);
function isEscapable(ch) {
return ESCAPE_C... | function htmlEscape(str) {
let result = '';
for (let i = 0; i < str.length; i++) {
if (isEscapable(str[i])) {
result += numericEntity(str[i]);
} else {
result += str[i];
}
}
return result;
}
| const assert = require('assert');
// Standard HTML escape: & -> &, < -> <, > -> >
// Our htmlEscape: & -> &, < -> <, > -> >
assert.strictEqual(htmlEscape('a & b'), 'a & b');
assert.strictEqual(htmlEscape('<div>'), '<div>');
assert.notStrictEqual(htmlEscape('a & b'), 'a & b');
asser... | assert.strictEqual(htmlEscape(''), '');
assert.strictEqual(htmlEscape('hello'), 'hello');
assert.strictEqual(htmlEscape('a@b.com'), 'a@b.com');
assert.strictEqual(htmlEscape('<script>alert("xss")</script>'),
'<script>alert("xss")</script>');
assert.strictEqual(htmlEscape('no special'), '... | pattern_matching |
24 | devbench-pattern-matching | javascript | // A memoization wrapper that uses a custom cache key strategy:
// - Cache key is JSON of ALL arguments (not just the first)
// - Object arguments have their keys sorted recursively for deterministic keys
// - Cache has a max size; when full, evicts the OLDEST entry (FIFO, not LRU)
function sortKeys(val) {
if (val... | function memoize(fn, maxSize = 100) {
const cache = new Map();
return function(...args) {
const key = makeCacheKey(args);
if (cache.has(key)) return cache.get(key);
const result = fn.apply(this, args);
if (cache.size >= maxSize) {
const firstKey = cache.keys().next().... | const assert = require('assert');
let calls = 0;
const add = memoize((a, b) => { calls++; return a + b; }, 3);
assert.strictEqual(add(1, 2), 3);
assert.strictEqual(calls, 1);
assert.strictEqual(add(1, 2), 3);
assert.strictEqual(calls, 1); // cached
assert.strictEqual(add(2, 1), 3);
assert.strictEqual(calls, 2); // ... | // Edge: zero-arg function
let zCalls = 0;
const zeroArg = memoize(() => { zCalls++; return 42; });
assert.strictEqual(zeroArg(), 42);
assert.strictEqual(zeroArg(), 42);
assert.strictEqual(zCalls, 1);
// Edge: null args
let nCalls = 0;
const nullFn = memoize((x) => { nCalls++; return x; }, 10);
nullFn(null);
nullFn(nu... | pattern_matching |
25 | devbench-pattern-matching | javascript | // Priority event emitter: listeners have a priority (lower = runs first).
// Default priority is 10. Listeners with the same priority run in insertion order.
class PriorityEmitter {
constructor() {
this.listeners = {};
}
on(event, fn, priority = 10) {
if (!this.listeners[event]) this.list... | emit(event, ...args) {
if (!this.listeners[event]) return false;
for (const listener of this.listeners[event]) {
listener.fn.apply(this, args);
}
return true;
}
once(event, fn, priority = 10) {
const wrapper = (...args) => {
this.off(event, wr... | }
const assert = require('assert');
const em = new PriorityEmitter();
const order = [];
em.on('test', () => order.push('low'), 20);
em.on('test', () => order.push('high'), 1);
em.on('test', () => order.push('mid'), 10);
em.emit('test');
assert.deepStrictEqual(order, ['high', 'mid', 'low']);
// once() should fire onl... | // Priority insertion order tie-breaking
const em3 = new PriorityEmitter();
const order3 = [];
em3.on('x', () => order3.push('a'), 5);
em3.on('x', () => order3.push('b'), 5);
em3.on('x', () => order3.push('c'), 5);
em3.emit('x');
assert.deepStrictEqual(order3, ['a', 'b', 'c']);
// off() works
const em4 = new PriorityE... | pattern_matching |
26 | devbench-pattern-matching | javascript | // Custom curry with placeholder support.
// PLACEHOLDER is a unique sentinel value (not undefined, not null).
// When calling a curried function, new arguments fill placeholders left-to-right
// BEFORE being appended to remaining positions.
// The function executes when all positions are filled (no placeholders remain... | function curry(fn) {
const arity = fn.length;
function curried(prev, incoming) {
let merged = [], ni = 0;
for (const a of prev) merged.push(a === PLACEHOLDER && ni < incoming.length ? incoming[ni++] : a);
while (ni < incoming.length) merged.push(incoming[ni++]);
const filled = me... | const assert = require('assert');
const add3 = curry((a, b, c) => a + b + c);
// Normal currying
assert.strictEqual(add3(1)(2)(3), 6);
assert.strictEqual(add3(1, 2)(3), 6);
assert.strictEqual(add3(1, 2, 3), 6);
// Placeholder usage: skip second arg, provide later
const _ = PLACEHOLDER;
const addWith1 = add3(1, _, 3)... | // Edge: all placeholders
const mul3 = curry((a, b, c) => a * b * c);
const allPh = mul3(_, _, _);
assert.strictEqual(allPh(2, 3, 4), 24);
// Placeholder then partial
const phThenPartial = mul3(_, 3, _);
assert.strictEqual(phThenPartial(2)(4), 24);
// Single-arg function
const double = curry((x) => x * 2);
assert.str... | pattern_matching |
27 | devbench-pattern-matching | javascript | // RingBuffer: fixed-capacity circular buffer.
// TWIST: when full, push() overwrites the MOST RECENT entry (not oldest).
// This preserves the oldest data, useful for keeping earliest observations.
// Iteration (toArray) returns elements from oldest to newest.
class RingBuffer {
constructor(capacity) {
th... | push(value) {
if (this.count < this.capacity) {
this.buffer[(this.head + this.count) % this.capacity] = value;
this.count++;
} else {
// Overwrite newest (last inserted position)
this.buffer[(this.head + this.count - 1) % this.capacity] = value;
... | }
const assert = require('assert');
const rb = new RingBuffer(3);
rb.push('a');
rb.push('b');
rb.push('c');
assert.deepStrictEqual(rb.toArray(), ['a', 'b', 'c']);
assert.strictEqual(rb.size, 3);
// When full, push overwrites the NEWEST (not oldest!)
rb.push('d');
assert.deepStrictEqual(rb.toArray(), ['a', 'b', 'd'])... | // Single element buffer
const rb1 = new RingBuffer(1);
rb1.push('x');
assert.deepStrictEqual(rb1.toArray(), ['x']);
rb1.push('y');
assert.deepStrictEqual(rb1.toArray(), ['y']); // overwrite newest = only element
// Two element buffer
const rb2 = new RingBuffer(2);
rb2.push(1);
rb2.push(2);
assert.deepStrictEqual(rb2... | pattern_matching |
28 | devbench-pattern-matching | javascript | // Template string interpolation engine with CUSTOM syntax:
// - Interpolation: #{varName} (not ${...})
// - Escape: \# to produce literal '#'
// - Nested property access: #{obj.prop.sub}
// - Missing variables resolve to empty string ''
function getNestedValue(obj, path) {
return path.split('.').reduce((curr, key... | function interpolate(template, context) {
let result = '', i = 0;
while (i < template.length) {
if (template[i] === '\\' && template[i + 1] === '#') { result += '#'; i += 2; }
else if (template[i] === '#' && template[i + 1] === '{') {
const end = template.indexOf('}', i + 2);
... | const assert = require('assert');
assert.strictEqual(
interpolate('Hello, #{name}!', { name: 'World' }),
'Hello, World!'
);
assert.strictEqual(
interpolate('#{user.first} #{user.last}', { user: { first: 'Jane', last: 'Doe' } }),
'Jane Doe'
);
// Missing var -> empty string
assert.strictEqual(interpolat... | // Nested missing
assert.strictEqual(interpolate('#{a.b.c}', { a: { b: {} } }), '');
// Multiple interpolations
assert.strictEqual(
interpolate('#{x}+#{y}=#{z}', { x: 1, y: 2, z: 3 }),
'1+2=3'
);
// No interpolation
assert.strictEqual(interpolate('plain text', {}), 'plain text');
// Empty template
assert.strict... | pattern_matching |
29 | devbench-pattern-matching | javascript | // Async utility library following a pattern: each function returns a Promise,
// accepts an options object, and handles edge cases with specific error types.
function delay(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
class RetryError extends Error {
constructor(message, attempts, lastErro... | async function retry(fn, { maxAttempts = 3, baseDelay = 100, backoffFactor = 2 } = {}) {
let lastError;
for (let attempt = 1; attempt <= maxAttempts; attempt++) {
try {
return await fn(attempt);
} catch (err) {
lastError = err;
if (attempt < maxAttempts) {
... | const assert = require('assert');
(async () => {
// Succeeds on 3rd attempt
let attempts = 0;
const result = await retry((attempt) => {
attempts++;
if (attempt < 3) throw new Error('not yet');
return 'success';
}, { maxAttempts: 5, baseDelay: 10 });
assert.strictEqual(result... | (async () => {
// Default options
let count = 0;
const res = await retry(() => { count++; if (count < 2) throw new Error('e'); return 'ok'; });
assert.strictEqual(res, 'ok');
// fn receives attempt number
const attempts = [];
await retry((attempt) => { attempts.push(attempt); if (attempt < ... | pattern_matching |
30 | devbench-pattern-matching | javascript | // Custom deep equality that differs from standard in specific ways:
// - NaN equals NaN (like Object.is)
// - -0 does NOT equal +0 (like Object.is)
// - Date objects compared by getTime()
// - RegExp objects compared by source + flags
// - Map and Set compared by entries
// - Does NOT follow prototype chains (own prop... | function deepEqual(a, b) {
if (a === b) return a !== 0 || 1 / a === 1 / b;
if (a !== a && b !== b) return true;
if (!isObject(a) || !isObject(b)) return false;
const tA = getType(a), tB = getType(b);
if (tA !== tB) return false;
if (tA === 'Date') return a.getTime() === b.getTime();
if (tA =... | const assert = require('assert');
// Standard behavior
assert.strictEqual(deepEqual(1, 1), true);
assert.strictEqual(deepEqual('a', 'a'), true);
assert.strictEqual(deepEqual({a: 1}, {a: 1}), true);
assert.strictEqual(deepEqual([1,2,3], [1,2,3]), true);
// NaN === NaN (differs from ===)
assert.strictEqual(deepEqual(Na... | // Nested objects with NaN
assert.strictEqual(deepEqual({x: NaN}, {x: NaN}), true);
assert.strictEqual(deepEqual({x: -0}, {x: +0}), false);
// Set comparison
assert.strictEqual(deepEqual(new Set([1,2,3]), new Set([3,2,1])), true);
assert.strictEqual(deepEqual(new Set([1,2]), new Set([1,2,3])), false);
// Map comparis... | pattern_matching |
31 | devbench-pattern-matching | javascript | const assert = require('assert');
// Custom encoding library with non-standard alphabets
// Each encoder takes a Buffer and returns an encoded string
function hexEncode(buf) {
const HEX_CHARS = 'fedcba9876543210';
let result = '';
for (let i = 0; i < buf.length; i++) {
result += HEX_CHARS[(buf[i] ... | function base64Encode(buf) {
const ALPHABET = 'zyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQPONMLKJIHGFEDCBA9876543210+/';
let bits = '';
for (let i = 0; i < buf.length; i++) {
bits += buf[i].toString(2).padStart(8, '0');
}
while (bits.length % 6 !== 0) bits += '0';
let result = '';
for (let ... |
// Verify base64Encode uses reversed alphabet (a=0, not A=0)
const test1 = base64Encode(Buffer.from([0]));
assert.strictEqual(test1, 'zz==', `Expected 'zz==' but got '${test1}'`);
const test2 = base64Encode(Buffer.from([255]));
assert.strictEqual(test2, '/D==', `Expected '/D==' but got '${test2}'`);
const test3 = ba... |
assert.strictEqual(base64Encode(Buffer.from([1])), 'zj==');
assert.strictEqual(base64Encode(Buffer.from([77])), 'gj==');
const hello = base64Encode(Buffer.from('Hello'));
assert.strictEqual(hello.length % 4, 0);
assert.strictEqual(base64Encode(Buffer.from([])), '');
assert.strictEqual(base64Encode(Buffer.from([0, 0]))... | pattern_matching |
32 | devbench-pattern-matching | javascript | const assert = require('assert');
// Custom URI encoding library
// These encoders use a NON-STANDARD safe set and lowercase hex
function encodePathSegment(str) {
let result = '';
for (let i = 0; i < str.length; i++) {
const c = str[i];
if (/[a-zA-Z0-9]/.test(c)) {
result += c;
... | function encodeQueryParam(str) {
let result = '';
for (let i = 0; i < str.length; i++) {
const c = str[i];
if (/[a-zA-Z0-9]/.test(c)) {
result += c;
} else if (c === ' ') {
result += '+';
} else {
const hex = Buffer.from(c).toString('hex');
... |
// Query param encoder: alphanumerics safe, space->'+', rest lowercase hex
assert.strictEqual(encodeQueryParam('hello world'), 'hello+world');
assert.strictEqual(encodeQueryParam('a=b'), 'a%3db');
assert.strictEqual(encodeQueryParam('a&b'), 'a%26b');
// Standard encodeURIComponent would give %20 for space, not +
// A... |
assert.strictEqual(encodeQueryParam(''), '');
assert.strictEqual(encodeQueryParam('abc'), 'abc');
assert.strictEqual(encodeQueryParam('a b c'), 'a+b+c');
assert.strictEqual(encodeQueryParam('100%'), '100%25');
assert.strictEqual(encodeQueryParam('key=val&x=y'), 'key%3dval%26x%3dy');
assert.strictEqual(encodeQueryParam... | pattern_matching |
33 | devbench-pattern-matching | javascript | const assert = require('assert');
// Custom markup escaping library
// Uses NUMERIC entity references, not named entities
// And escapes in a specific priority order
function escapeXml(str) {
let result = '';
for (let i = 0; i < str.length; i++) {
switch (str[i]) {
case '&': result += '... | function escapeHtml(str) {
let result = '';
for (let i = 0; i < str.length; i++) {
const code = str.charCodeAt(i);
if (code === 38) { result += '&'; }
else if (code === 60) { result += '<'; }
else if (code === 62) { result += '>'; }
else if (code === 34) { res... |
// Uses numeric entities, NOT named entities like & < etc.
assert.strictEqual(escapeHtml('<p>'), '<p>');
assert.strictEqual(escapeHtml('&'), '&');
assert.strictEqual(escapeHtml('"'), '"');
// Named entities would be wrong
assert.notStrictEqual(escapeHtml('<'), '<');
assert.notStrictEqual(esc... |
assert.strictEqual(escapeHtml(''), '');
assert.strictEqual(escapeHtml('hello'), 'hello');
assert.strictEqual(escapeHtml("it's"), "it's");
assert.strictEqual(escapeHtml('a < b & c > d'), 'a < b & c > d');
assert.strictEqual(escapeHtml('\u00fc'), 'ü');
assert.strictEqual(escapeHtml('normal text 123'... | pattern_matching |
34 | devbench-pattern-matching | javascript | const assert = require('assert');
// Custom collection processing library
// Each processor wraps arrays with metadata tracking
function customMap(arr, fn) {
const result = [];
const trace = [];
for (let i = 0; i < arr.length; i++) {
const mapped = fn(arr[i], i);
result.push(mapped);
... | function customReduce(arr, fn, initial) {
let acc = initial;
const trace = [];
for (let i = 0; i < arr.length; i++) {
const prev = acc;
acc = fn(acc, arr[i], i);
trace.push({ index: i, input: arr[i], accBefore: prev, accAfter: acc });
}
return { result: acc, trace, operation:... |
// customReduce wraps result with metadata, just like customMap and customFilter
const sum = customReduce([1,2,3,4], (acc, x) => acc + x, 0);
assert.strictEqual(sum.result, 10);
assert.strictEqual(sum.operation, 'reduce');
assert.strictEqual(sum.count, 4);
assert.strictEqual(sum.trace.length, 4);
assert.deepStrictEqua... |
const product = customReduce([2,3,4], (acc, x) => acc * x, 1);
assert.strictEqual(product.result, 24);
assert.strictEqual(product.operation, 'reduce');
assert.strictEqual(product.count, 3);
const empty = customReduce([], (acc, x) => acc + x, 42);
assert.strictEqual(empty.result, 42);
assert.strictEqual(empty.count, 0... | pattern_matching |
35 | devbench-pattern-matching | javascript | const assert = require('assert');
// Custom event system with priority-based listener ordering
// Lower priority number = runs first
class PriorityEventBus {
constructor() {
this._handlers = {};
}
on(event, handler, priority = 10) {
if (!this._handlers[event]) this._handlers[event] = [];
... | off(event, handler) {
if (this._handlers[event])
this._handlers[event] = this._handlers[event].filter(h => h.handler !== handler);
return this;
}
once(event, handler, priority = 10) {
const wrapper = (...args) => { this.off(event, wrapper); return handler(...args); };
... | }
// Test priority ordering
const bus = new PriorityEventBus();
const order = [];
bus.on('test', () => order.push('B'), 5);
bus.on('test', () => order.push('A'), 1);
bus.on('test', () => order.push('C'), 10);
bus.emit('test');
assert.deepStrictEqual(order, ['A', 'B', 'C']);
// Test off
const handler = () => 'removed'... |
const bus2 = new PriorityEventBus();
// once should only fire once
let count = 0;
bus2.once('evt', () => ++count);
bus2.emit('evt');
bus2.emit('evt');
assert.strictEqual(count, 1);
// off on non-existent event should not throw
bus2.off('nonexistent', () => {});
// once with priority should respect priority
const seq... | pattern_matching |
36 | devbench-pattern-matching | javascript | const assert = require('assert');
// Custom template engine with specific syntax rules:
// - {{var}} for variable substitution
// - {{var|filter}} for filtered substitution
// - {{#if var}}...{{/if}} for conditionals
// Filters are: upper, lower, capitalize, reverse
function applyFilter(value, filter) {
switch (f... | function render(template, data) {
// Process innermost conditionals first, then work outward
let result = template;
let prev;
do {
prev = result;
result = result.replace(/\{\{#if (\w+)\}\}((?:(?!\{\{#if )[\s\S])*?)\{\{\/if\}\}/g, (match, key, body) => {
const val = data[key];... |
// Basic variable substitution
assert.strictEqual(render('Hello {{name}}!', { name: 'Alice' }), 'Hello Alice!');
// Filter support
assert.strictEqual(render('{{x|upper}}', { x: 'hello' }), 'HELLO');
assert.strictEqual(render('{{x|reverse}}', { x: 'abc' }), 'cba');
// Conditional blocks
assert.strictEqual(
render... |
// Nested conditionals
assert.strictEqual(
render('{{#if a}}A{{#if b}}B{{/if}}{{/if}}', { a: true, b: true }),
'AB'
);
assert.strictEqual(
render('{{#if a}}A{{#if b}}B{{/if}}{{/if}}', { a: true, b: false }),
'A'
);
assert.strictEqual(
render('{{#if a}}A{{#if b}}B{{/if}}{{/if}}', { a: false, b: true... | pattern_matching |
37 | devbench-pattern-matching | javascript | const assert = require('assert');
// Custom iterator factory library
// Each factory returns an object with next() that returns { value, done, index }
// Unlike standard iterators, 'done' is true ON the last valid item (not after it)
function rangeIter(start, end) {
let i = start;
return {
next() {
... | function stringIter(str) {
let i = 0;
return {
next() {
if (i >= str.length) return { value: undefined, done: true, index: -1 };
const val = str[i];
const idx = i++;
return { value: val, done: i >= str.length, index: idx };
}
};
}
|
// stringIter follows the same non-standard done semantics
const s = stringIter('abc');
assert.deepStrictEqual(s.next(), { value: 'a', done: false, index: 0 });
assert.deepStrictEqual(s.next(), { value: 'b', done: false, index: 1 });
assert.deepStrictEqual(s.next(), { value: 'c', done: true, index: 2 }); // done ON l... |
// Single character
const s1 = stringIter('X');
assert.deepStrictEqual(s1.next(), { value: 'X', done: true, index: 0 });
assert.deepStrictEqual(s1.next(), { value: undefined, done: true, index: -1 });
// Empty string
const s2 = stringIter('');
assert.deepStrictEqual(s2.next(), { value: undefined, done: true, index: -... | pattern_matching |
38 | devbench-pattern-matching | javascript | const assert = require('assert');
// Custom hash library where each hash function:
// 1. Returns a FIXED-WIDTH hex string
// 2. Uses XOR folding (not standard hash algorithms)
// 3. Returns { hash, width } metadata
function hash8(str) {
let h = 0;
for (let i = 0; i < str.length; i++) {
h ^= str.charCo... | function hash32(str) {
let h = 0;
for (let i = 0; i < str.length; i++) {
h ^= str.charCodeAt(i);
h = ((h << 7) | (h >>> 25)) & 0xffffffff;
}
return { hash: (h >>> 0).toString(16).padStart(8, '0'), width: 32 };
}
|
// hash32 follows the same pattern: XOR + rotate, fixed-width hex output
assert.strictEqual(hash32('').hash, '00000000');
assert.strictEqual(hash32('').width, 32);
// Verify fixed width (8 hex chars)
assert.strictEqual(hash32('a').hash.length, 8);
assert.strictEqual(hash32('test').hash.length, 8);
// Rotation: 8-bit... |
// Deterministic
assert.strictEqual(hash32('hello').hash, hash32('hello').hash);
// Different inputs should (usually) differ
assert.notStrictEqual(hash32('abc').hash, hash32('xyz').hash);
// Returns correct metadata
assert.strictEqual(hash32('anything').width, 32);
// Verify the rotation pattern: 8-bit <<3, 16-bit ... | pattern_matching |
39 | devbench-pattern-matching | javascript | const assert = require('assert');
// Custom retry library with specific backoff patterns
// Each retry function records attempt metadata
function retryLinear(fn, maxRetries, baseDelay) {
const attempts = [];
return new Promise(async (resolve, reject) => {
for (let i = 0; i <= maxRetries; i++) {
... | function retryExponential(fn, maxRetries, baseDelay) {
const attempts = [];
return new Promise(async (resolve, reject) => {
for (let i = 0; i <= maxRetries; i++) {
const delay = i === 0 ? 0 : baseDelay * Math.pow(2, i - 1);
if (i > 0) await new Promise(r => setTimeout(r, delay));... |
// Test retryExponential succeeds on 3rd attempt
let callCount = 0;
retryExponential(
(attempt) => {
callCount++;
if (attempt < 2) throw new Error('not yet');
return 'done';
},
5,
10
).then(({ result, attempts }) => {
assert.strictEqual(result, 'done');
assert.strictEqua... |
// Test immediate success
retryExponential(
() => 'immediate',
3,
100
).then(({ result, attempts }) => {
assert.strictEqual(result, 'immediate');
assert.strictEqual(attempts.length, 1);
assert.strictEqual(attempts[0].delay, 0);
assert.strictEqual(attempts[0].success, true);
});
// Test max... | pattern_matching |
40 | devbench-pattern-matching | javascript | const assert = require('assert');
// Custom deep operations library
// Each function returns { result, metadata } with operation stats
function deepFreeze(obj, depth = 0) {
const metadata = { frozen: 0, maxDepth: depth };
if (obj === null || typeof obj !== 'object') return { result: obj, metadata };
Objec... | function deepClone(obj, depth = 0, seen = new Map()) {
const metadata = { cloned: 0, maxDepth: depth };
if (obj === null || typeof obj !== 'object') return { result: obj, metadata };
if (seen.has(obj)) return { result: seen.get(obj), metadata };
const result = Array.isArray(obj) ? [] : {};
seen.set(... |
// deepClone follows the same metadata pattern
const c1 = deepClone({ a: 1, b: { c: 2 } });
assert.deepStrictEqual(c1.result, { a: 1, b: { c: 2 } });
assert.strictEqual(c1.metadata.cloned, 2);
assert.strictEqual(c1.metadata.maxDepth, 1);
// Verify it's a true deep clone
c1.result.b.c = 99;
const c2 = deepClone({ a: 1... |
// Null and primitives
const p1 = deepClone(null);
assert.deepStrictEqual(p1, { result: null, metadata: { cloned: 0, maxDepth: 0 } });
const p2 = deepClone(42);
assert.deepStrictEqual(p2, { result: 42, metadata: { cloned: 0, maxDepth: 0 } });
// Nested arrays
const a1 = deepClone([[1], [2], [3]]);
assert.deepStrictE... | pattern_matching |
41 | devbench-pattern-matching | javascript | const STANDARD_B64 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
const REVERSE_B64 = '/+9876543210zyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQPONMLKJIHGFEDCBA';
function bytesToBits(buf) {
let bits = '';
for (let i = 0; i < buf.length; i++) {
bits += buf[i].toString(2).padStart(8, '0');... | function base64Encode(data, alphabet = REVERSE_B64, pad = '.') {
const buf = Buffer.from(data);
if (buf.length === 0) return '';
const groups = sixBitGroups(buf);
let result = groups.map(g => alphabet[parseInt(g, 2)]).join('');
const remainder = buf.length % 3;
if (remainder === 1) result += pad... | const assert = require('assert');
assert.strictEqual(bytesToBits(Buffer.from([0x66])), '01100110');
assert.strictEqual(sixBitGroups(Buffer.from([0x66])).length, 2);
// This base64 encoder uses REVERSE alphabet and '.' padding by default.
// Standard base64 for 'f' is 'Zg=='. Ours differs.
const encoded = base64Encode(... | assert.strictEqual(base64Encode('', REVERSE_B64, '.'), '');
assert.strictEqual(base64Encode('f', STANDARD_B64, '='), 'Zg==');
assert.strictEqual(base64Encode('fo', STANDARD_B64, '='), 'Zm8=');
assert.strictEqual(base64Encode('foo', STANDARD_B64, '='), 'Zm9v');
assert.strictEqual(base64Encode('foob', STANDARD_B64, '='),... | pattern_matching |
42 | devbench-pattern-matching | javascript | function hexEncode(charCode) {
return '%' + charCode.toString(16).toUpperCase().padStart(2, '0');
}
function isAlpha(c) {
return (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z');
}
function htmlEscape(str) {
// Pattern: only escape &, <, >, and leave everything else
let out = '';
for (const c of s... | function urlEncode(str, safeChars = '!~') {
let out = '';
for (const c of str) {
if (isAlpha(c) || safeChars.includes(c)) { out += c; }
else { for (const b of Buffer.from(c, 'utf8')) out += hexEncode(b); }
}
return out;
}
| const assert = require('assert');
// This urlEncode treats ONLY alpha + safeChars as safe.
// Digits are NOT safe by default (unlike standard encodeURIComponent).
assert.strictEqual(urlEncode('hello'), 'hello');
assert.strictEqual(urlEncode('a1b'), 'a%31b'); // digit '1' is encoded!
assert.strictEqual(urlEncode('a!b')... | assert.strictEqual(urlEncode(''), '');
assert.strictEqual(urlEncode('abc'), 'abc');
assert.strictEqual(urlEncode('123'), '%31%32%33');
assert.strictEqual(urlEncode('a+b'), 'a%2Bb');
assert.strictEqual(urlEncode('a/b'), 'a%2Fb');
assert.strictEqual(urlEncode('!~'), '!~');
assert.strictEqual(urlEncode('a@b'), 'a%40b');
/... | pattern_matching |
43 | devbench-pattern-matching | javascript | class PriorityEmitter {
constructor() {
this._listeners = {};
}
on(event, fn, priority = 10) {
if (!this._listeners[event]) this._listeners[event] = [];
this._listeners[event].push({ fn, priority, once: false });
// Keep sorted by priority ascending
this._listeners[e... | once(event, fn, priority = 10) {
if (!this._listeners[event]) this._listeners[event] = [];
this._listeners[event].push({ fn, priority, once: true });
this._listeners[event].sort((a, b) => a.priority - b.priority);
return this;
}
emit(event, ...args) {
if (!this._liste... | off(event, fn) {
if (!this._listeners[event]) return this;
this._listeners[event] = this._listeners[event].filter(l => l.fn !== fn);
return this;
}
}
const assert = require('assert');
const em = new PriorityEmitter();
const order = [];
em.on('test', () => order.push('low'), 20);
em.on('... | // Priority ordering with once
const em3 = new PriorityEmitter();
const seq = [];
em3.once('x', () => seq.push('once-5'), 5);
em3.on('x', () => seq.push('on-10'), 10);
em3.once('x', () => seq.push('once-1'), 1);
em3.emit('x');
assert.deepStrictEqual(seq, ['once-1', 'once-5', 'on-10']);
// Second emit: only persistent l... | pattern_matching |
44 | devbench-pattern-matching | javascript | function shallowEqual(a, b) {
if (typeof a !== typeof b) return false;
if (typeof a === 'number') return Math.abs(a - b) < 1e-9;
return a === b;
}
function arrayEqual(a, b) {
// Pattern: arrays are compared as SORTED SETS (order-independent)
if (a.length !== b.length) return false;
const sa = [... | function deepEqual(a, b) {
if (a === b) return true;
if (a == null || b == null) return a === b;
if (typeof a === 'number' && typeof b === 'number') return Math.abs(a - b) < 1e-9;
if (typeof a !== typeof b) return false;
if (Array.isArray(a) !== Array.isArray(b)) return false;
if (Array.isArray(... | const assert = require('assert');
// Numbers with epsilon
assert.strictEqual(deepEqual(0.1 + 0.2, 0.3), true);
// Arrays as sets (order independent)
assert.strictEqual(deepEqual([1, 2, 3], [3, 1, 2]), true);
assert.strictEqual(deepEqual([1, 2], [2, 3]), false);
// Nested objects
assert.strictEqual(deepEqual({a: 1}, {a:... | // Array order independence (the key trap)
assert.strictEqual(deepEqual([3, 2, 1], [1, 2, 3]), true);
assert.strictEqual(deepEqual(['b', 'a'], ['a', 'b']), true);
// Nested arrays as sets
assert.strictEqual(deepEqual([[1, 2], [3, 4]], [[3, 4], [1, 2]]), true);
// Epsilon for deeply nested numbers
assert.strictEqual(dee... | pattern_matching |
45 | devbench-pattern-matching | javascript | function delay(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
async function retryLinear(fn, maxRetries = 3, delayMs = 100) {
for (let i = 0; i <= maxRetries; i++) {
try {
return await fn();
} catch (e) {
if (i === maxRetries) throw e;
await ... | async function retryExponential(fn, maxRetries = 3, baseDelay = 100, maxDelay = 500) {
for (let i = 0; i <= maxRetries; i++) {
try {
return await fn();
} catch (e) {
if (i === maxRetries) throw e;
const d = Math.min(baseDelay * Math.pow(2, i), maxDelay);
... | const assert = require('assert');
async function testRetry() {
// Test successful retry
let attempts = 0;
const result = await retryExponential(() => {
attempts++;
if (attempts < 3) throw new Error('fail');
return 'ok';
});
assert.strictEqual(result, 'ok');
assert.strict... | async function testAssertions() {
// All retries exhausted -> throws
let count = 0;
try {
await retryExponential(() => { count++; throw new Error('always'); }, 2, 10, 50);
assert.fail('should have thrown');
} catch (e) {
assert.strictEqual(e.message, 'always');
assert.str... | pattern_matching |
46 | devbench-pattern-matching | javascript | function isAlphanumeric(c) {
return (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9');
}
function decimalEntityEncode(str, safeChars = '') {
// Encodes everything that is NOT alphanumeric and NOT in safeChars
// Uses &#DD; decimal numeric character references (NOT named entities)
... | function htmlSafeEncode(str, extraSafe = ' ') {
let out = '';
for (const c of str) {
if (isAlphanumeric(c) || c === ' ' || extraSafe.includes(c)) {
out += c;
} else {
out += '&#' + c.charCodeAt(0) + ';';
}
}
return out;
}
| const assert = require('assert');
// decimalEntityEncode: everything non-alphanumeric is &#DD;
assert.strictEqual(decimalEntityEncode('a<b'), 'a<b');
assert.strictEqual(decimalEntityEncode('a&b'), 'a&b');
// NOT < or & — always decimal numeric refs
// htmlSafeEncode: spaces are safe by default
assert.st... | assert.strictEqual(htmlSafeEncode(''), '');
assert.strictEqual(htmlSafeEncode('abc123'), 'abc123');
assert.strictEqual(htmlSafeEncode('a+b=c'), 'a+b=c');
assert.strictEqual(htmlSafeEncode('"quotes"'), '"quotes"');
// Space is safe by default
assert.strictEqual(htmlSafeEncode('a b'), 'a b');
// With extr... | pattern_matching |
47 | devbench-pattern-matching | javascript | function* chunkArray(arr, size) {
// Non-overlapping chunks
for (let i = 0; i < arr.length; i += size) {
yield arr.slice(i, i + size);
}
}
function* chunkString(str, size) {
// Same pattern for strings
for (let i = 0; i < str.length; i += size) {
yield str.slice(i, i + size);
}
... | function* slidingWindow(arr, size, step = 1) {
// Overlapping chunks: advance by step (not size)
for (let i = 0; i <= arr.length - size; i += step) {
yield arr.slice(i, i + size);
}
}
| const assert = require('assert');
// Non-overlapping chunks
assert.deepStrictEqual([...chunkArray([1,2,3,4,5], 2)], [[1,2],[3,4],[5]]);
assert.deepStrictEqual([...chunkString('abcde', 2)], ['ab','cd','e']);
// Sliding window: overlapping with step=1 by default
const windows = [...slidingWindow([1,2,3,4], 3)];
assert.d... | // Window equals array length
assert.deepStrictEqual([...slidingWindow([1,2,3], 3)], [[1,2,3]]);
// Window of 1
assert.deepStrictEqual([...slidingWindow([1,2,3], 1)], [[1],[2],[3]]);
// Step larger than 1
assert.deepStrictEqual([...slidingWindow([1,2,3,4,5,6], 2, 3)], [[1,2],[4,5]]);
// Empty result when array smaller ... | pattern_matching |
48 | devbench-pattern-matching | javascript | async function runSequential(tasks) {
const results = [];
for (const task of tasks) {
results.push(await task());
}
return results;
}
async function runParallel(tasks) {
return Promise.all(tasks.map(t => t()));
}
| async function runPooled(tasks, concurrency = 2) {
const results = new Array(tasks.length);
let next = 0;
const worker = async () => {
while (next < tasks.length) { const i = next++; results[i] = await tasks[i](); }
};
const w = Array.from({length: Math.min(concurrency, tasks.length)}, () =>... | const assert = require('assert');
async function testPool() {
const log = [];
const makeFn = (id, ms) => async () => {
log.push('start-' + id);
await new Promise(r => setTimeout(r, ms));
log.push('end-' + id);
return id;
};
const tasks = [makeFn('a', 50), makeFn('b', 30... | async function testPoolAssertions() {
// Results in correct order regardless of completion order
const tasks2 = [
async () => { await new Promise(r => setTimeout(r, 40)); return 1; },
async () => { await new Promise(r => setTimeout(r, 10)); return 2; },
async () => { await new Promise(r ... | pattern_matching |
49 | devbench-pattern-matching | javascript | function pipeline(...fns) {
// Standard pipeline: each fn gets result of previous. Stops on error.
return function(input) {
let result = input;
for (const fn of fns) {
result = fn(result);
}
return result;
};
}
| function recoveryPipeline(...fns) {
return function(input) {
let value = input, error = null;
for (const fn of fns) {
try { value = fn(value, error); error = null; }
catch (e) { error = e; value = null; }
}
if (error) throw error;
return value;
};
... | const assert = require('assert');
// Standard pipeline
const double = pipeline(x => x * 2, x => x + 1);
assert.strictEqual(double(5), 11);
// Recovery pipeline: error is passed to next fn which can recover
const recover = recoveryPipeline(
(v) => { throw new Error('boom'); },
(v, err) => err ? 'recovered:' + ... | // Chain of errors and recoveries
const chain = recoveryPipeline(
(v) => v + 1,
(v) => { throw new Error('e1'); },
(v, err) => { if (err) return 100; return v; },
(v) => v * 2
);
assert.strictEqual(chain(0), 200);
// Last fn throws -> pipeline throws
assert.throws(() => {
const p = recoveryPipeline... | pattern_matching |
50 | devbench-pattern-matching | javascript | function toHexByte(n) {
return n.toString(16).padStart(2, '0').toUpperCase();
}
function simpleHex(data) {
const buf = Buffer.from(data);
return Array.from(buf).map(b => toHexByte(b)).join('');
}
function spacedHex(data) {
const buf = Buffer.from(data);
return Array.from(buf).map(b => toHexByte(b)... | function checksumHex(data, groupSize = 4, sep = '-') {
const buf = Buffer.from(data);
if (buf.length === 0) return '';
let checksum = 0;
const hexBytes = Array.from(buf).map(b => { checksum ^= b; return toHexByte(b); });
hexBytes.push(toHexByte(checksum));
const groups = [];
for (let i = 0; ... | const assert = require('assert');
// simpleHex: no spaces
assert.strictEqual(simpleHex('AB'), '4142');
// spacedHex: space-separated
assert.strictEqual(spacedHex('AB'), '41 42');
// checksumHex: grouped with checksum byte appended
// 'AB' = [0x41, 0x42], checksum = 0x41 ^ 0x42 = 0x03
// 3 hex bytes: 41,42,03 -> groupe... | // Empty input
assert.strictEqual(checksumHex(''), '');
// Single byte
assert.strictEqual(checksumHex('X'), toHexByte(0x58) + toHexByte(0x58));
// Checksum correctness
// 'Hi' = [0x48, 0x69], XOR = 0x48 ^ 0x69 = 0x21
// 3 hex bytes: 48,69,21 -> grouped by 4: '486921'
assert.strictEqual(checksumHex('Hi'), '486921');
// ... | pattern_matching |
1 | devbench-syntax-completion | javascript | function createResource(name) {
return { name, closed: false, close() { this.closed = true; } };
}
async function processResources(names) {
const results = [];
for (const name of names) {
const resource = createResource(name);
try {
if (name.startsWith('bad')) {
... | results.push({ name, status: 'error', message: err.message });
} finally {
resource.close();
results.push({ name, closed: resource.closed });
}
| }
return results;
}
async function test1() {
const res = await processResources(['good1', 'bad2', 'good3']);
return res;
}
| const assert = require('assert');
test1().then(res => {
assert.strictEqual(res.length, 6);
assert.deepStrictEqual(res[0], { name: 'good1', status: 'ok' });
assert.deepStrictEqual(res[1], { name: 'good1', closed: true });
assert.deepStrictEqual(res[2], { name: 'bad2', status: 'error', message: 'Invalid ... | syntax_completion |
2 | devbench-syntax-completion | javascript | async function* resilientItems(batch) {
for (const item of batch.items ?? []) {
try {
yield { id: batch.id, item };
} catch (err) {
yield { id: batch.id, recovered: err.message };
}
}
return batch.id + ':done';
}
async function* source(list) {
for (const ... | const marker = yield* resilientItems(batch);
audit.push('delegated:' + marker);
} catch (err) {
audit.push('error:' + err.message);
yield { id: batch.id, error: err.message };
} finally {
audit.push('done:' + batch.i... | }
} finally {
audit.push('close');
}
}
const assert = require('assert');
(async () => {
const audit = [];
const gen = streamBatches(source([{ id: 'a', items: [1, 2] }]), audit);
assert.deepStrictEqual(await gen.next(), { value: { id: 'a', item: 1 }, done: false });
assert.deepS... | (async () => {
const audit = [];
const out = [];
for await (const value of streamBatches(source([
{ id: 'ok', items: ['x'] },
{ id: 'bad', fail: true },
{ id: 'skip', skip: true, items: ['z'] }
]), audit)) out.push(value);
assert.deepStrictEqual(out, [
{ id: 'ok', ite... | syntax_completion |
3 | devbench-syntax-completion | javascript | function unpackEnvelope(packet, primaryKey, fallbackKey) {
const {
id = 'missing',
routes: [
{ name: firstRoute = 'root', hops: [firstHop = 'start', ...otherHops] = [] } = {},
...otherRoutes
] = [],
[primaryKey]: {
enabled: primaryEnabled = false,
... | [fallbackKey]: {
enabled: fallbackEnabled = primaryEnabled,
limits: { soft: fallbackSoft = primarySoft - 1, hard: fallbackHard = primaryHard + fallbackSoft } = {},
windows: [{ start: fallbackStart = 0, end: fallbackEnd = fallbackStart + fallbackSoft } = {}, ...fallbackWindows... |
return {
id,
route: { firstRoute, firstHop, otherHops, otherRouteCount: otherRoutes.length },
primary: { primaryEnabled, primarySoft, primaryHard, primaryStart, primaryEnd, primaryWindowCount: primaryWindows.length, primaryExtra },
fallback: { fallbackEnabled, fallbackSoft, fallback... | const inherited = unpackEnvelope({
main: { enabled: true, limits: { soft: 4, hard: 9 } },
routes: [{}],
meta: { owners: [{}], flags: { archived: true } }
}, 'main', 'backup');
assert.strictEqual(inherited.fallback.fallbackEnabled, true);
assert.strictEqual(inherited.fallback.fallbackSoft, 3);
assert.strictE... | syntax_completion |
4 | devbench-syntax-completion | javascript | function parseConfig(raw) {
const {
server: {
host = 'localhost',
port = 3000,
ssl: {
enabled: sslEnabled = false,
cert: sslCert = null,
} = {},
} = {},
database: {
| url: dbUrl = 'mongodb://localhost:27017',
name: dbName = 'default',
options: {
poolSize: dbPoolSize = 5,
retryWrites: dbRetryWrites = true,
} = {},
} = {},
logging: {
level: logLevel = 'info',
format:... | } = raw || {};
return {
host, port, sslEnabled, sslCert,
dbUrl, dbName, dbPoolSize, dbRetryWrites,
logLevel, logFormat,
};
}
| const assert = require('assert');
const full = parseConfig({
server: { host: 'prod.example.com', port: 8080, ssl: { enabled: true, cert: '/path/to/cert' } },
database: { url: 'mongodb://prod:27017', name: 'mydb', options: { poolSize: 20, retryWrites: false } },
logging: { level: 'debug', format: 'text' },
... | syntax_completion |
5 | devbench-syntax-completion | javascript | async function* paginate(fetchPage) {
let page = 0;
let hasMore = true;
try {
while (hasMore) {
const result = await fetchPage(page);
if (!result || result.items.length === 0) {
hasMore = false;
} else {
| for (const item of result.items) {
yield item;
}
hasMore = result.hasMore !== false;
page++;
}
}
} finally {
yield { done: true, totalPages: page };
}
| }
async function collectAll(gen) {
const items = [];
for await (const item of gen) {
items.push(item);
}
return items;
}
| const assert = require('assert');
const mockPages = [
{ items: ['a', 'b'], hasMore: true },
{ items: ['c'], hasMore: true },
{ items: ['d', 'e'], hasMore: false },
];
async function mockFetch(page) {
return mockPages[page] || null;
}
collectAll(paginate(mockFetch)).then(result => {
assert.strictE... | syntax_completion |
6 | devbench-syntax-completion | javascript | function createValidatedObject(schema) {
const data = {};
const log = [];
return new Proxy(data, {
set(target, prop, value) {
const rule = schema[prop];
if (!rule) {
log.push({ action: 'reject', prop, reason: 'unknown' });
return false;
... | target[prop] = rule.transform ? rule.transform(value) : value;
log.push({ action: 'set', prop, value: target[prop] });
return true;
},
get(target, prop) {
if (prop === '_log') return [...log];
if (prop === '_data') return { ...target };
... | });
}
| const assert = require('assert');
const obj = createValidatedObject({
name: { type: 'string', transform: v => v.trim().toLowerCase() },
age: { type: 'number', min: 0 },
});
obj.name = ' Alice ';
assert.strictEqual(obj.name, 'alice');
obj.age = 25;
assert.strictEqual(obj.age, 25);
const r1 = Reflect.set(ob... | syntax_completion |
7 | devbench-syntax-completion | javascript | function batchProcess(items, processor) {
const results = { succeeded: [], failed: [], retried: [] };
return Promise.allSettled(
items.map(item =>
processor(item)
.then(value => ({ item, value, attempt: 1 }))
.catch(err =>
| processor(item)
.then(value => {
results.retried.push(item);
return { item, value, attempt: 2 };
})
.catch(retryErr => {
throw { item, errors: [... | )
).then(outcomes => {
for (const outcome of outcomes) {
if (outcome.status === 'fulfilled') {
results.succeeded.push(outcome.value);
} else {
results.failed.push(outcome.reason);
}
}
return results;
});
}
| const assert = require('assert');
let callCounts = {};
function testProcessor(item) {
callCounts[item] = (callCounts[item] || 0) + 1;
if (item === 'fail-always') return Promise.reject(new Error('permanent'));
if (item === 'fail-once' && callCounts[item] === 1) return Promise.reject(new Error('transient'));... | syntax_completion |
8 | devbench-syntax-completion | javascript | const _history = Symbol('history');
class ReactiveMap {
#data = new Map();
[_history] = [];
constructor(entries = []) {
for (const [k, v] of entries) {
this.#data.set(k, v);
}
}
get size() {
return this.#data.size;
}
set(key, value) {
if (typeo... | this.#data.set(key, value);
this[_history].push({ type: old === undefined ? 'add' : 'update', key, oldValue: old, newValue: value });
return this;
}
get(key) { return this.#data.get(key); }
getHistory(key) {
return key === undefined ? [...this[_history]] : this[_history].fi... |
[Symbol.iterator]() {
return this.#data[Symbol.iterator]();
}
}
| const assert = require('assert');
const rm = new ReactiveMap([['x', 1]]);
assert.strictEqual(rm.size, 1);
assert.strictEqual(rm.get('x'), 1);
rm.set('x', 2).set('y', 3);
assert.strictEqual(rm.get('x'), 2);
assert.strictEqual(rm.get('y'), 3);
assert.strictEqual(rm.size, 2);
const hist = rm.getHistory();
assert.strict... | syntax_completion |
9 | devbench-syntax-completion | javascript | function createPipeline(...stages) {
return async function execute(input) {
const context = { input, results: [], errors: [] };
for (const [index, stage] of stages.entries()) {
const { name = `stage_${index}`, transform, fallback = null } = stage;
try {
const ... | const output = await transform(prevOutput, context);
context.results.push({ name, output });
} catch (err) {
if (fallback) {
const fbResult = await fallback(err, context);
context.results.push({ name, output: fbResult, f... | }
return context;
};
}
| const assert = require('assert');
const pipeline = createPipeline(
{ name: 'double', transform: async (v) => v * 2 },
{ name: 'addTen', transform: async (v) => v + 10 },
{
name: 'failSafe',
transform: async () => { throw new Error('boom'); },
fallback: async (err) => 'recovered:' + ... | syntax_completion |
10 | devbench-syntax-completion | javascript | async function* walkTree(node, path = []) {
const currentPath = [...path, node.name];
if (node.type === 'leaf') {
yield { path: currentPath, value: node.value, depth: currentPath.length };
return;
}
if (node.type === 'branch') {
yield { path: currentPath, type: 'enter', depth: cu... | yield* walkTree(child, currentPath);
} catch (err) {
yield {
path: [...currentPath, child.name || `child_${idx}`],
error: err.message,
depth: currentPath.length + 1,
};
... | }
async function collectTree(node) {
const events = [];
for await (const event of walkTree(node)) {
events.push(event);
}
return events;
}
| const assert = require('assert');
const tree = {
name: 'root', type: 'branch', children: [
{ name: 'a', type: 'leaf', value: 1 },
{ name: 'b', type: 'branch', children: [
{ name: 'c', type: 'leaf', value: 2 },
{ name: 'd', type: 'leaf', value: 3 },
]},
{ name... | syntax_completion |
11 | devbench-syntax-completion | javascript | function retryGroups(groups, worker) {
const audit = [];
return Promise.all(
groups.map(group =>
Promise.allSettled(
group.items.map((item, index) =>
worker(item)
.then(value => ({ group: group.name, item, value, attempt: 1 }))
... | new Promise(resolve => {
setTimeout(() => {
audit.push(`retry:${group.name}:${index}`);
resolve(worker(item)
.then(value => ({ group: group.name, it... | )
).then(results => ({
group: group.name,
values: results.map(r => r.value)
}))
)
).then(groups => ({ groups, audit }));
}
const assert = require('assert');
(async () => {
const calls = {};
const worker = (item) => {
c... | (async () => {
const seen = [];
const worker = (item) => {
seen.push(item);
if (item === 'late') return Promise.reject(new Error('late-fail'));
return Promise.resolve(item + item);
};
const res = await retryGroups([{ name: 'C', delay: 0, items: ['x', 'late'] }], worker);
asse... | syntax_completion |
12 | devbench-syntax-completion | javascript | // Async generator that yields values from an array with a delay.
// Simulates an async data stream.
async function* asyncStream(items, delayMs) {
for (const item of items) {
await new Promise(r => setTimeout(r, delayMs));
yield item;
}
}
// Collects values from an async generator until a predi... | for await (const value of asyncGen) {
if (!predicate(value)) break;
results.push(value);
}
return results;
| }
async function test12() {
const assert = require('assert');
const r1 = await takeWhile(
asyncStream([1, 2, 3, 4, 5], 1),
x => x < 4
);
assert.deepStrictEqual(r1, [1, 2, 3]);
const r2 = await takeWhile(
asyncStream(['a', 'b', 'c'], 1),
x => x !== 'b'
);
as... | async function hidden12() {
const assert = require('assert');
// Predicate always true => take all
const r3 = await takeWhile(
asyncStream([10, 20, 30], 1),
() => true
);
assert.deepStrictEqual(r3, [10, 20, 30]);
// Predicate fails immediately => empty
const r4 = await take... | syntax_completion |
13 | devbench-syntax-completion | javascript | // Extracts configuration from a nested config object using
// destructuring with computed property keys, defaults, and renaming.
function extractConfig(config, primaryKey, fallbackKey) {
const {
[primaryKey]: {
enabled: isEnabled = false,
retries: maxRetries = 3,
timeout... | [fallbackKey]: {
enabled: fallbackEnabled = false,
retries: fallbackRetries = 1,
...extraFallback
} = {},
version = '1.0',
} = config;
|
return {
primary: { isEnabled, maxRetries, timeoutMs, extra: extraPrimary },
fallback: { fallbackEnabled, fallbackRetries, extra: extraFallback },
version,
};
}
const assert = require('assert');
const cfg = {
database: { enabled: true, retries: 5, timeout: 3000, pool: 10 },
cac... | // Missing keys => defaults apply
const result2 = extractConfig({}, 'db', 'cache');
assert.deepStrictEqual(result2.primary, { isEnabled: false, maxRetries: 3, timeoutMs: 1000, extra: {} });
assert.deepStrictEqual(result2.fallback, { fallbackEnabled: false, fallbackRetries: 1, extra: {} });
assert.strictEqual(result2.ve... | syntax_completion |
14 | devbench-syntax-completion | javascript | // Sub-generator that yields numbers and handles thrown errors
// by yielding an error marker and continuing.
function* resilientRange(start, end) {
for (let i = start; i < end; i++) {
try {
yield i;
} catch (e) {
yield `error:${e.message}`;
}
}
}
// Delegating g... | for (const [start, end] of ranges) {
yield* resilientRange(start, end);
}
| }
const assert = require('assert');
// Basic delegation
const g1 = chainedRanges([0, 3], [10, 13]);
assert.deepStrictEqual(
[...g1],
[0, 1, 2, 10, 11, 12]
);
// Error forwarding through yield*
const g2 = chainedRanges([0, 3]);
assert.deepStrictEqual(g2.next(), { value: 0, done: false });
assert.deepStrictEqu... | // Empty ranges
const g3 = chainedRanges([5, 5], [0, 2]);
assert.deepStrictEqual([...g3], [0, 1]);
// Single range
const g4 = chainedRanges([0, 1]);
assert.deepStrictEqual([...g4], [0]);
// Multiple errors
const g5 = chainedRanges([0, 4]);
g5.next(); // 0
g5.throw(new Error('e1')); // error:e1
g5.next(); // 1
g5.next... | syntax_completion |
15 | devbench-syntax-completion | javascript | // Processes a list of tokens and categorizes them using a reducer.
// The switch uses intentional fallthrough for grouping:
// 'add', 'subtract' => 'arithmetic'
// 'and', 'or', 'not' => 'logical'
// 'if', 'else', 'while', 'for' => 'control'
// anything else => 'unknown'
// Returns an object mapping categories ... | case 'if':
case 'else':
case 'while':
case 'for':
category = 'control';
break;
default:
category = 'unknown';
}
| if (!acc[category]) acc[category] = [];
acc[category].push(token);
return acc;
}, {});
}
const assert = require('assert');
const r1 = categorizeTokens(['add', 'if', 'or', 'subtract', 'foo', 'while']);
assert.deepStrictEqual(r1.arithmetic, ['add', 'subtract']);
assert.deepStrictEqual(r1.log... | // Empty input
const r2 = categorizeTokens([]);
assert.deepStrictEqual(r2, {});
// All unknown
const r3 = categorizeTokens(['xyz', 'abc']);
assert.deepStrictEqual(r3, { unknown: ['xyz', 'abc'] });
// All logical
const r4 = categorizeTokens(['and', 'or', 'not', 'and']);
assert.deepStrictEqual(r4, { logical: ['and', 'o... | syntax_completion |
16 | devbench-syntax-completion | javascript | // Tagged template that sanitizes interpolated values:
// - strings: HTML-escape < > & " '
// - numbers: format with commas (e.g., 1000 => "1,000")
// - arrays: join with ", " after recursively sanitizing each element
// - other: convert to string and HTML-escape
function safe(strings, ...values) {
function escape(... | function process(val) {
if (Array.isArray(val)) return val.map(process).join(', ');
if (typeof val === 'number') return formatNum(val);
return escape(val);
}
return strings.reduce((out, str, i) =>
out + str + (i < values.length ? process(values[i]) : ''), '');
| }
const assert = require('assert');
const name = '<script>';
const count = 1500;
const items = ['a', 'b', 'c'];
const result = safe`User ${name} has ${count} items: ${items}`;
assert.strictEqual(result, 'User <script> has 1,500 items: a, b, c');
const r2 = safe`Price: ${2500.5} for "${'"quoted"'}"`;
assert.st... | // Nested arrays
const r3 = safe`${[1, '<b>', [2, 3]]}`;
assert.strictEqual(r3, '1, <b>, 2, 3');
// No interpolations
const r4 = safe`plain text`;
assert.strictEqual(r4, 'plain text');
// Single value
const r5 = safe`${42}`;
assert.strictEqual(r5, '42');
// Ampersand in string
const r6 = safe`${'a&b'}`;
assert... | syntax_completion |
17 | devbench-syntax-completion | javascript | // A ring buffer with a fixed capacity that overwrites oldest entries.
// Uses private fields and implements Symbol.iterator to yield
// elements in insertion order (oldest to newest).
class RingBuffer {
#buffer;
#head;
#count;
#capacity;
static #defaultCapacity;
static {
RingBuffer.#de... | [Symbol.iterator]() {
let i = 0, count = this.#count, head = this.#head, cap = this.#capacity, buf = this.#buffer;
return { next() {
if (i < count) return { value: buf[(head + i++) % cap], done: false };
return { done: true, value: undefined };
}};
}
| }
const assert = require('assert');
const rb = new RingBuffer(3);
rb.push('a');
rb.push('b');
rb.push('c');
assert.deepStrictEqual([...rb], ['a', 'b', 'c']);
assert.strictEqual(rb.size, 3);
// Overwrite oldest
rb.push('d');
assert.deepStrictEqual([...rb], ['b', 'c', 'd']);
rb.push('e');
assert.deepStrictEqual([...r... | // Default capacity
const rb2 = new RingBuffer();
for (let i = 0; i < 10; i++) rb2.push(i);
assert.strictEqual(rb2.size, 8);
assert.deepStrictEqual([...rb2], [2, 3, 4, 5, 6, 7, 8, 9]);
// Capacity 1
const rb3 = new RingBuffer(1);
rb3.push('x');
rb3.push('y');
assert.deepStrictEqual([...rb3], ['y']);
// Empty
const rb... | syntax_completion |
18 | devbench-syntax-completion | javascript | // Fetches data from multiple sources in parallel.
// If any source fails, retries that source sequentially with exponential backoff.
// Returns an object mapping source names to their results.
// maxRetries applies per-source.
async function fetchWithRetry(sources, maxRetries = 2) {
// sources: [{ name: string, fe... | for (const { source, reason } of failed) {
let lastErr = reason, ok = false;
for (let a = 0; a < maxRetries && !ok; a++) {
try { await new Promise(r => setTimeout(r, 2 ** a)); results[source.name] = await source.fetch(); ok = true; }
catch (e) { lastErr = e; }
}
... | }
async function test18() {
const assert = require('assert');
let callCount = 0;
const sources = [
{ name: 'fast', fetch: () => Promise.resolve('ok') },
{
name: 'flaky', fetch: () => {
callCount++;
if (callCount <= 2) return Promise.reject(new Er... | async function hidden18() {
const assert = require('assert');
// All succeed in parallel => no retries
const r3 = await fetchWithRetry([
{ name: 'a', fetch: () => Promise.resolve(1) },
{ name: 'b', fetch: () => Promise.resolve(2) },
]);
assert.deepStrictEqual(r3, { a: 1, b: 2 });
... | syntax_completion |
19 | devbench-syntax-completion | javascript | // Parses a log string containing lines in the format:
// [LEVEL] YYYY-MM-DD message text
// Returns an array of objects { level, date, message } for lines
// matching a given level filter. Uses named capture groups.
function parseLogs(logText, levelFilter = null) {
const pattern = /^\[(?<level>\w+)\]\s+(?<date>\d{... | const m = pattern.exec(line);
if (!m) return null;
return {
level: m.groups.level,
date: m.groups.date,
message: m.groups.message.trim(),
};
})
.filter(entry => entry !== null)
.filter(entry => levelF... | }
const assert = require('assert');
const logs = `[INFO] 2024-01-15 Server started
[ERROR] 2024-01-15 Connection failed
[WARN] 2024-01-16 High memory usage
garbage line
[INFO] 2024-01-16 Request processed`;
const all = parseLogs(logs);
assert.strictEqual(all.length, 4);
assert.deepStrictEqual(all[0], { level: 'INFO'... | // Empty string
const r2 = parseLogs('');
assert.deepStrictEqual(r2, []);
// No matches
const r3 = parseLogs('no valid lines here');
assert.deepStrictEqual(r3, []);
// Filter returns empty when no matching level
const r4 = parseLogs('[DEBUG] 2024-01-01 test', 'ERROR');
assert.deepStrictEqual(r4, []);
// All same lev... | syntax_completion |
20 | devbench-syntax-completion | javascript | // A cache that holds weak references to values and tracks cleanup.
// When a cached value is garbage collected, its key is removed from
// the metadata map and the cleanup callback is invoked.
class WeakCache {
#refs = new Map(); // key => WeakRef
#meta = new Map(); // key => metadata
#cleane... | get(key) {
const ref = this.#refs.get(key);
return ref ? ref.deref() : undefined;
}
has(key) {
const ref = this.#refs.get(key);
return ref !== undefined && ref.deref() !== undefined;
}
getMeta(key) { return this.#meta.get(key); }
get cleanedKeys() { return [...thi... | }
const assert = require('assert');
const cache = new WeakCache();
let obj1 = { data: 'hello' };
let obj2 = { data: 'world' };
cache.set('k1', obj1, { created: Date.now() });
cache.set('k2', obj2);
// Objects are still alive
assert.strictEqual(cache.get('k1').data, 'hello');
assert.strictEqual(cache.get('k2').data,... | // Multiple sets with same key overwrites
const cache2 = new WeakCache();
let a = { x: 1 };
let b = { x: 2 };
cache2.set('dup', a, { v: 1 });
cache2.set('dup', b, { v: 2 });
assert.strictEqual(cache2.get('dup').x, 2);
assert.strictEqual(cache2.getMeta('dup').v, 2);
// cleanedKeys is initially empty (no GC happened)
as... | syntax_completion |
21 | devbench-syntax-completion | javascript | function findFirstAboveThreshold(groups, threshold) {
// groups is an array of {name, scores: number[]}
// Returns {group: name, score: value} for the FIRST score above threshold
// found in a depth-first scan. Returns null if none found.
let result = null;
outerLoop:
for (const {name, scores} o... | for (const score of scores) {
if (score > threshold) {
result = {group: name, score};
break outerLoop;
}
}
| }
return result;
}
const groups = [
{name: 'A', scores: [10, 20, 30]},
{name: 'B', scores: [5, 50, 15]},
{name: 'C', scores: [100]}
];
const r = findFirstAboveThreshold(groups, 25);
console.log(r);
| const assert = require('assert');
assert.deepStrictEqual(r, {group: 'A', score: 30});
const r2 = findFirstAboveThreshold(groups, 99);
assert.deepStrictEqual(r2, {group: 'C', score: 100});
const r3 = findFirstAboveThreshold(groups, 999);
assert.strictEqual(r3, null);
const r4 = findFirstAboveThreshold([], 0);
assert.str... | syntax_completion |
22 | devbench-syntax-completion | javascript | // groupAndTransform: groups items by category, then returns
// an array of {category, total, items: string[]} for groups with total > minTotal
function groupAndTransform(items, minTotal) {
// items: [{category: string, value: number, label: string}]
const grouped = items.reduce((acc, item) => {
if (!ac... | .map(([category, catItems]) => ({
category,
total: catItems.reduce((s, i) => s + i.value, 0),
items: catItems.map(i => i.label)
}))
.filter(g => g.total > minTotal)
.sort((a, b) => b.total - a.total);
| }
const data = [
{category: 'fruit', value: 3, label: 'apple'},
{category: 'fruit', value: 5, label: 'banana'},
{category: 'veggie', value: 2, label: 'carrot'},
{category: 'veggie', value: 1, label: 'pea'},
{category: 'grain', value: 10, label: 'rice'}
];
const result = groupAndTransform(data, 5);
... | const assert = require('assert');
assert.strictEqual(result.length, 2);
assert.strictEqual(result[0].category, 'grain');
assert.strictEqual(result[0].total, 10);
assert.deepStrictEqual(result[0].items, ['rice']);
assert.strictEqual(result[1].category, 'fruit');
assert.strictEqual(result[1].total, 8);
assert.deepStrictE... | syntax_completion |
23 | devbench-syntax-completion | javascript | class AsyncCache {
constructor(loader, ttlMs) {
this._cache = new Map();
this._loader = loader;
this._ttlMs = ttlMs;
this._ready = (async () => {
| try {
const initial = await this._loader('__init__');
if (initial !== undefined) {
this._cache.set('__init__', {value: initial, expires: Date.now() + this._ttlMs});
}
return true;
} catch (err) {
... | }
async get(key) {
await this._ready;
const entry = this._cache.get(key);
if (entry && entry.expires > Date.now()) return entry.value;
const val = await this._loader(key);
this._cache.set(key, {value: val, expires: Date.now() + this._ttlMs});
return val;
}
}
... | const assert = require('assert');
testCache().then(r => {
assert.strictEqual(r.ready, true);
assert.strictEqual(r.v1, 'initialized');
assert.strictEqual(r.v2, 'loaded:hello');
// Test with failing loader
const failLoader = async (key) => { throw new Error('fail'); };
const cache2 = new AsyncCac... | syntax_completion |
24 | devbench-syntax-completion | javascript | function* paginatedFetch(pages, pageSize) {
// Yields items from pages one at a time.
// After each page, yields a separator {type: 'page-break', page: N}.
// If a page has fewer items than pageSize, yields {type: 'end', total: count}
// and returns the total count.
let count = 0;
for (let i = 0... | for (const item of page) {
yield {type: 'item', value: item};
count++;
}
if (page.length < pageSize) {
yield {type: 'end', total: count};
return count;
}
if (i < pages.length - 1) {
yield {type: 'page-break', page: i + 1... | }
yield {type: 'end', total: count};
return count;
}
const pages = [[1, 2, 3], [4, 5, 6], [7, 8]];
const gen = paginatedFetch(pages, 3);
const results = [];
while (true) {
const next = gen.next();
if (next.done) break;
results.push(next.value);
}
console.log(JSON.stringify(results));
| const assert = require('assert');
// Page 1: 3 items + page-break
assert.deepStrictEqual(results[0], {type: 'item', value: 1});
assert.deepStrictEqual(results[1], {type: 'item', value: 2});
assert.deepStrictEqual(results[2], {type: 'item', value: 3});
assert.deepStrictEqual(results[3], {type: 'page-break', page: 1});
/... | syntax_completion |
25 | devbench-syntax-completion | javascript | function extractUserMetrics(response) {
// Extracts metrics from a deeply nested API response.
// Uses optional chaining and nullish coalescing throughout.
// Returns {name, email, score, badges, lastLogin}
const user = response?.data?.users?.[0];
| return {
name: user?.profile?.displayName ?? user?.username ?? 'anonymous',
email: user?.contacts?.find(c => c.type === 'email')?.value ?? null,
score: user?.metrics?.scores?.reduce((a, b) => a + b, 0) ?? 0,
badges: user?.achievements?.map(a => a?.badge?.name)?.filter(Boolean) ?? [],... | }
// Test with full data
const fullResponse = {
data: {
users: [{
username: 'jdoe',
profile: {displayName: 'John Doe'},
contacts: [{type: 'phone', value: '555'}, {type: 'email', value: 'j@d.com'}],
metrics: {scores: [10, 20, 30]},
achievements: [{... | const assert = require('assert');
assert.strictEqual(r1.name, 'John Doe');
assert.strictEqual(r1.email, 'j@d.com');
assert.strictEqual(r1.score, 60);
assert.deepStrictEqual(r1.badges, ['gold', 'silver']);
assert.strictEqual(r1.lastLogin, 't3');
// Test with partial data
const partial = {data: {users: [{username: 'bob'... | syntax_completion |
26 | devbench-syntax-completion | javascript | function timedOperation(workFn, timeoutMs) {
// Returns a promise that:
// 1. Runs workFn (which returns a promise)
// 2. Races it against a timeout
// 3. On success: resolves with {status: 'ok', result, elapsed}
// 4. On timeout: resolves with {status: 'timeout', elapsed: timeoutMs}
// 5. On er... | let settled = false;
const timer = setTimeout(() => {
if (!settled) { settled = true; resolve({status: 'timeout', elapsed: timeoutMs}); }
}, timeoutMs);
workFn().then((result) => {
if (!settled) { settled = true; clearTimeout(timer); resolve({status: 'ok', result,... | });
}
// Tests
async function runTests() {
// Test 1: Successful fast operation
const r1 = await timedOperation(() => Promise.resolve(42), 1000);
console.log('r1:', JSON.stringify(r1));
// Test 2: Error operation
const r2 = await timedOperation(() => Promise.reject(new Error('boom')), 1000);
... | const assert = require('assert');
runTests().then(({r1, r2, r3}) => {
assert.strictEqual(r1.status, 'ok');
assert.strictEqual(r1.result, 42);
assert(r1.elapsed < 100, 'fast op should be quick');
assert.strictEqual(r2.status, 'error');
assert.strictEqual(r2.message, 'boom');
assert(r2.elapsed < ... | syntax_completion |
27 | devbench-syntax-completion | javascript | const TYPE_KEY = Symbol('type');
const makeEntity = (kind, initialData) => {
const _log = [];
const prefix = `[${kind}]`;
return {
[TYPE_KEY]: kind,
[`get${kind.charAt(0).toUpperCase() + kind.slice(1)}Info`]() {
return `${prefix} entries: ${this._count}`;
},
...in... | _count: 0,
get summary() {
return `${prefix} ${this._count} items, log: ${_log.length}`;
},
set data(val) {
_log.push({action: 'set', value: val, at: _log.length});
this._count++;
},
getLog() {
return [..._log];
}
... | };
const entity = makeEntity('widget', {color: 'blue'});
entity.data = 'first';
entity.data = 'second';
entity.data = 'third';
console.log(entity.summary);
console.log(entity.getWidgetInfo());
console.log(entity[TYPE_KEY]);
console.log(entity.color);
console.log(entity.getLog().length);
| const assert = require('assert');
assert.strictEqual(entity[TYPE_KEY], 'widget');
assert.strictEqual(entity.color, 'blue');
assert.strictEqual(entity._count, 3);
assert.strictEqual(entity.summary, '[widget] 3 items, log: 3');
assert.strictEqual(entity.getWidgetInfo(), '[widget] entries: 3');
const log = entity.getLog()... | syntax_completion |
28 | devbench-syntax-completion | javascript | function buildConfig(
{
server: {
host = 'localhost',
port = 3000,
ssl: {
enabled: sslEnabled = false,
cert: sslCert = null,
...sslRest
} = {}
} = {},
logging: {
level: logLevel = 'inf... | return {
serverConfig: {host, port, ssl: {enabled: sslEnabled, cert: sslCert, ...sslRest}},
loggingConfig: {level: logLevel, outputs: [primaryOutput, ...extraOutputs]},
extra: otherOptions
};
| }
// Test with full config
const full = buildConfig({
server: {host: '0.0.0.0', port: 8080, ssl: {enabled: true, cert: '/path/cert.pem', key: '/path/key.pem'}},
logging: {level: 'debug', outputs: ['file', 'syslog', 'console']},
version: '2.0',
debug: true
});
console.log(JSON.stringify(full, null, 2));... | const assert = require('assert');
// Full config assertions
assert.strictEqual(full.serverConfig.host, '0.0.0.0');
assert.strictEqual(full.serverConfig.port, 8080);
assert.strictEqual(full.serverConfig.ssl.enabled, true);
assert.strictEqual(full.serverConfig.ssl.cert, '/path/cert.pem');
assert.strictEqual(full.serverCo... | syntax_completion |
29 | devbench-syntax-completion | javascript | class AsyncPipeline {
constructor(stages) {
// stages: array of async functions, each takes input and returns output
this._stages = stages;
this._results = [];
}
async run(input) {
this._results = [];
let current = input;
for (const stage of this._stages) {
... | return {
async next() {
if (index < results.length) {
return {value: {stage: index, result: results[index++]}, done: false};
}
return {value: undefined, done: true};
},
[Symbol.asyncIterator]() {
... | }
async function testPipeline() {
const pipeline = new AsyncPipeline([
async (x) => x * 2,
async (x) => x + 10,
async (x) => x.toString()
]);
const final = await pipeline.run(5);
console.log('Final:', final);
const collected = [];
for await (const entry of pipeline) {
... | const assert = require('assert');
testPipeline().then(({final, collected}) => {
assert.strictEqual(final, '20');
assert.strictEqual(collected.length, 3);
assert.deepStrictEqual(collected[0], {stage: 0, result: 10});
assert.deepStrictEqual(collected[1], {stage: 1, result: 20});
assert.deepStrictEqual... | syntax_completion |
30 | devbench-syntax-completion | javascript | function createValidator(schema) {
// schema: {fieldName: {type: 'string'|'number'|'boolean'|'array', required, min?, max?}}
// Returns a Proxy that validates on set and throws on invalid assignments.
const data = {};
return new Proxy(data, {
set(target, prop, value) {
const rule = s... | case 'boolean':
if (typeof value !== 'boolean') throw new TypeError(`${prop} must be boolean`);
break;
case 'array': {
if (!Array.isArray(value)) throw new TypeError(`${prop} must be array`);
if (rule.min !==... | },
get(target, prop) {
if (prop === '__data') return {...target};
if (prop === '__schema') return schema;
return target[prop];
}
});
}
const user = createValidator({
name: {type: 'string', required: true, min: 1, max: 50},
age: {type: 'number', re... | const assert = require('assert');
assert.strictEqual(user.name, 'Alice');
assert.strictEqual(user.age, 30);
assert.strictEqual(user.active, true);
assert.deepStrictEqual(user.tags, ['admin', 'user']);
assert.strictEqual(user.extraField, 'allowed');
// Type errors
assert.throws(() => { user.name = 123; }, TypeError);
a... | syntax_completion |
31 | devbench-syntax-completion | javascript | const assert = require('assert');
const data = [
{ dept: 'eng', name: 'Alice', salary: 100 },
{ dept: 'eng', name: 'Bob', salary: 120 },
{ dept: 'sales', name: 'Carol', salary: 90 },
{ dept: 'sales', name: 'Dave', salary: 95 },
{ dept: 'eng', name: 'Eve', salary: 110 },
];
const tagged = data.map((row, i) =... | const grouped = tagged.reduce((acc, row) => ({
...acc,
[row.dept]: [...(acc[row.dept] || []), row],
}), {});
const summary = Object.entries(grouped).map(([dept, rows]) => ({
dept, count: rows.length,
total: rows.reduce((s, r) => s + r.salary, 0),
avg: Math.round(rows.reduce((s, r) => s + r.salary, 0... |
assert.strictEqual(Object.keys(grouped).length, 2);
assert.strictEqual(grouped['eng'].length, 3);
assert.strictEqual(grouped['sales'].length, 2);
const eng = summary.find(s => s.dept === 'eng');
const sales = summary.find(s => s.dept === 'sales');
assert.strictEqual(eng.count, 3);
assert.strictEqual(eng.total, 330);
a... |
assert.strictEqual(tagged.length, 5);
assert.strictEqual(Array.isArray(summary), true);
assert.strictEqual(summary.length, 2);
for (const s of summary) {
assert.ok('dept' in s && 'count' in s && 'total' in s && 'avg' in s);
}
| syntax_completion |
32 | devbench-syntax-completion | javascript | const assert = require('assert');
async function* range(start, end) {
for (let i = start; i < end; i++) yield i;
}
async function collectAll(gen) {
const items = [];
for await (const item of gen) items.push(item);
return items;
}
const pipeLog = [];
// filteredPipeline: async generator that filters+... | async function* filteredPipeline(source, filterFn, transformFn) {
pipeLog.push('open');
try {
for await (const item of source) {
if (filterFn(item)) { pipeLog.push('yield:' + item); yield transformFn(item); }
}
} catch (err) { pipeLog.push('error:' + err.message); throw err; }
... |
(async () => {
pipeLog.length = 0;
const results = await collectAll(filteredPipeline(range(0, 6), x => x % 2 === 0, x => x * 2));
assert.deepStrictEqual(results, [0, 4, 8]);
assert.strictEqual(pipeLog[0], 'open');
assert.strictEqual(pipeLog[pipeLog.length - 1], 'close');
assert.ok(pipeLog.inclu... |
assert.strictEqual(filteredPipeline.constructor.name, 'AsyncGeneratorFunction');
assert.ok(Array.isArray(pipeLog));
| syntax_completion |
33 | devbench-syntax-completion | javascript | const assert = require('assert');
class Shape {
#name;
constructor(name) { this.#name = name; this._transforms = []; }
get name() { return this.#name; }
transform(t) { this._transforms.push(t); return this; }
describe() { return `${this.#name}[${this._transforms.join(',')}]`; }
}
class Polygon ext... | class RegularPolygon extends Polygon {
#count; #len;
constructor(name, count, len) {
super(name, Array(count).fill(len));
this.#count = count; this.#len = len;
}
get count() { return this.#count; }
get sideLength() { return this.#len; }
area() { return (this.#count * this.#len **... |
const hex = new RegularPolygon('hexagon', 6, 10);
assert.ok(hex instanceof RegularPolygon);
assert.ok(hex instanceof Polygon);
assert.ok(hex instanceof Shape);
assert.strictEqual(hex.sides.length, 6);
assert.strictEqual(hex.perimeter(), 60);
assert.strictEqual(hex.count, 6);
assert.strictEqual(hex.sideLength, 10);
ass... |
const tri = new RegularPolygon('triangle', 3, 7);
assert.strictEqual(tri.perimeter(), 21);
assert.strictEqual(tri.count, 3);
assert.strictEqual(tri.sideLength, 7);
assert.ok(tri instanceof Polygon);
const triArea = (3 * 49) / (4 * Math.tan(Math.PI / 3));
assert.ok(Math.abs(tri.area() - triArea) < 0.001);
assert.strict... | syntax_completion |
34 | devbench-syntax-completion | javascript | const assert = require('assert');
function upper(strings, ...values) {
let result = '';
strings.forEach((str, i) => { result += str; if (i < values.length) result += String(values[i]).toUpperCase(); });
return result;
}
assert.strictEqual(upper`hello ${'world'}!`, 'hello WORLD!');
// sql tag: parameterize... | function sql(strings, ...params) {
let text = ''; const values = [];
strings.forEach((str, i) => {
text += str;
if (i >= params.length) return;
if (Array.isArray(params[i])) {
text += params[i].map((_, j) => `$${values.length + j + 1}`).join(', ');
values.push(...... |
const q1 = sql`SELECT * FROM users WHERE id = ${42}`;
assert.strictEqual(q1.text, 'SELECT * FROM users WHERE id = $1');
assert.deepStrictEqual(q1.values, [42]);
const q2 = sql`INSERT INTO t (a, b) VALUES (${1}, ${'hello'})`;
assert.strictEqual(q2.text, 'INSERT INTO t (a, b) VALUES ($1, $2)');
const q3 = sql`SELECT *... |
const q5 = sql`SELECT 1`;
assert.strictEqual(q5.text, 'SELECT 1');
assert.deepStrictEqual(q5.values, []);
const q7 = sql`UPDATE t SET x = ${99} WHERE a IN (${[1,2]}) AND b IN (${[3,4]})`;
assert.strictEqual(q7.text, 'UPDATE t SET x = $1 WHERE a IN ($2, $3) AND b IN ($4, $5)');
assert.deepStrictEqual(q7.values, [99, 1... | syntax_completion |
35 | devbench-syntax-completion | javascript | const assert = require('assert');
// createStore: returns a revocable proxy that tracks get/set/delete in a history array
// Access _history and _revoke properties without logging them
function createStore(initial = {}) {
const history = [];
const data = { ...initial };
const handler = {
get(targe... | deleteProperty(target, prop) {
if (prop in target) {
history.push({ op: 'delete', prop, old: target[prop] });
delete target[prop];
}
return true;
},
};
const { proxy, revoke } = Proxy.revocable(data, handler);
return proxy;
... |
const store = createStore({ x: 1, y: 2 });
store.x;
assert.deepStrictEqual(store._history[0], { op: 'get', prop: 'x', value: 1 });
store.z = 3;
const setEntry = store._history.find(e => e.op === 'set' && e.prop === 'z');
assert.ok(setEntry);
assert.strictEqual(setEntry.old, undefined);
store.x = 10;
const overwrite ... |
const s2 = createStore({ a: 'hello' });
assert.strictEqual(s2.a, 'hello');
s2.b = 42;
assert.strictEqual(s2.b, 42);
delete s2.nonexistent;
const dels = s2._history.filter(e => e.op === 'delete' && e.prop === 'nonexistent');
assert.strictEqual(dels.length, 0);
const rk = s2._revoke;
rk();
assert.throws(() => { s2.a; },... | syntax_completion |
36 | devbench-syntax-completion | javascript | const assert = require('assert');
const registry = new Map();
function registerPlugin(name, factory) { registry.set(name, { factory, instance: null, loaded: false }); }
registerPlugin('math', () => ({ add: (a, b) => a + b, mul: (a, b) => a * b }));
registerPlugin('string', () => ({ reverse: s => s.split('').reverse()... | async function pipeline(pluginCalls) {
let result = pluginCalls[0].input;
for (const { plugin, method, args = [] } of pluginCalls) {
const mod = await loadPlugin(plugin);
if (typeof mod[method] !== 'function') {
throw new Error('Method "' + method + '" not found in "' + plugin + '"')... |
(async () => {
const math = await loadPlugin('math');
assert.strictEqual(math.add(2, 3), 5);
const math2 = await loadPlugin('math');
assert.strictEqual(math, math2);
const r1 = await pipeline([
{ plugin: 'math', method: 'add', args: [10], input: 5 },
{ plugin: 'math', method: 'mul'... |
assert.strictEqual(typeof pipeline, 'function');
assert.strictEqual(registry.size, 2);
assert.ok(registry.has('math'));
assert.ok(registry.has('string'));
| syntax_completion |
37 | devbench-syntax-completion | javascript | const assert = require('assert');
class LazyRange {
constructor(start, end, step = 1) { this.start = start; this.end = end; this.step = step; }
[Symbol.iterator]() {
let current = this.start; const end = this.end, step = this.step;
return { next() { if (current < end) { const v = current; curre... | class LazyChain {
constructor(...iterables) { this._its = iterables; }
*[Symbol.iterator]() { for (const it of this._its) yield* it; }
map(fn) { const s = this; return _wrapLazy(function*() { let i = 0; for (const x of s) yield fn(x, i++); }); }
filter(fn) { const s = this; return _wrapLazy(function*() ... |
const chain1 = new LazyChain(new LazyRange(0, 3), new LazyRange(10, 13), [20, 21]);
assert.deepStrictEqual(chain1.toArray(), [0, 1, 2, 10, 11, 12, 20, 21]);
assert.deepStrictEqual([...chain1], [0, 1, 2, 10, 11, 12, 20, 21]);
const mapped = chain1.map(x => x * 2);
assert.deepStrictEqual(mapped.toArray(), [0, 2, 4, 20,... |
const empty = new LazyChain();
assert.deepStrictEqual(empty.toArray(), []);
const single = new LazyChain([1, 2, 3]);
assert.deepStrictEqual(single.toArray(), [1, 2, 3]);
const withIdx = new LazyChain([10, 20, 30]).map((x, i) => x + i);
assert.deepStrictEqual(withIdx.toArray(), [10, 21, 32]);
const chained = new LazyCh... | syntax_completion |
38 | devbench-syntax-completion | javascript | const assert = require('assert');
const defaultConfig = {
server: { host: 'localhost', port: 3000, ssl: false },
db: { host: 'localhost', port: 5432, name: 'app', pool: { min: 2, max: 10 } },
logging: { level: 'info', format: 'json', outputs: ['stdout'] },
};
// parseConfig: deep destructuring with defaul... | const { server: { host: sH = 'localhost', port: sP = 3000, ssl = false, ...sR } = {},
db: { host: dH = 'localhost', port: dP = 5432, name: dN = 'app',
pool: { min: pMi = 2, max: pMa = 10 } = {}, ...dR } = {},
logging: { level = 'info', format: lF = 'json',
outputs: [... |
const c1 = parseConfig();
assert.strictEqual(c1.server.host, 'localhost');
assert.strictEqual(c1.server.port, 3000);
assert.strictEqual(c1.db.pool.min, 2);
assert.strictEqual(c1.db.pool.max, 10);
assert.strictEqual(c1.logging.primaryOutput, 'stdout');
assert.deepStrictEqual(c1.logging.otherOutputs, []);
assert.deepStr... |
const c3 = parseConfig({ server: {}, db: {}, logging: {} });
assert.strictEqual(c3.server.host, 'localhost');
assert.strictEqual(c3.db.port, 5432);
assert.strictEqual(c3.logging.level, 'info');
const c4 = parseConfig({ server: { host: 'prod', timeout: 5000 } });
assert.strictEqual(c4.server.host, 'prod');
assert.stric... | syntax_completion |
39 | devbench-syntax-completion | javascript | const assert = require('assert');
// createTransaction: runs steps sequentially, rolls back completed steps on failure
// Each step has {name, fn, undoFn?, input?}. Logs name:start, name:ok, name:fail:msg, undo:name
function createTransaction() {
const log = [];
function run(steps) {
let chain = Promis... | .catch(err => {
if (!log.some(e => e === name + ':ok' || e.startsWith(name + ':fail'))) log.push(name + ':fail:' + err.message);
let rb = Promise.resolve();
for (const d of done) rb = rb.then(() => d.undoFn()).then(() => log.push('undo:' + d.na... |
(async () => {
const t1 = createTransaction();
const r1 = await t1.run([
{ name: 'A', fn: () => 1, undoFn: () => {}, input: null },
{ name: 'B', fn: x => x + 10, undoFn: () => {} },
{ name: 'C', fn: x => x * 2, undoFn: () => {} },
]);
assert.strictEqual(r1.success, true);
as... |
(async () => {
const t3 = createTransaction();
const r3 = await t3.run([{ name: 'only', fn: () => 42, undoFn: () => {}, input: null }]);
assert.strictEqual(r3.success, true);
assert.strictEqual(r3.result, 42);
const t4 = createTransaction();
const r4 = await t4.run([{ name: 'fail', fn: () => {... | syntax_completion |
40 | devbench-syntax-completion | javascript | const assert = require('assert');
// LRU cache: WeakRef for objects, shim for primitives
// has() does NOT update access order
class WeakCache {
constructor(maxSize) {
this._max = maxSize;
this._cache = new Map();
this._order = [];
this._registry = new FinalizationRegistry(key => {... | get(key) {
if (!this._cache.has(key)) return undefined;
const ref = this._cache.get(key); const val = ref.deref();
if (val === undefined && ref instanceof WeakRef) { this._cache.delete(key); this._order = this._order.filter(k => k !== key); return undefined; }
this._order = this._ord... | }
const cache = new WeakCache(3);
const obj1 = { id: 1 }, obj2 = { id: 2 };
cache.set('a', obj1);
cache.set('b', obj2);
cache.set('c', 42);
assert.strictEqual(cache.size, 3);
assert.deepStrictEqual(cache.get('a'), obj1);
assert.deepStrictEqual(cache.get('b'), obj2);
assert.strictEqual(cache.get('c'), 42);
assert.stric... |
const c2 = new WeakCache(2);
c2.set('x', { v: 1 });
c2.set('y', { v: 2 });
c2.get('x');
c2.set('z', { v: 3 });
assert.strictEqual(c2.has('y'), false);
assert.strictEqual(c2.has('x'), true);
assert.strictEqual(c2.has('z'), true);
const c3 = new WeakCache(5);
c3.set('num', 42);
c3.set('str', 'hello');
assert.strictEqual... | syntax_completion |
41 | devbench-syntax-completion | javascript | function createAsyncCounter() {
let count = 0;
const log = [];
const increment = async (amount) => {
await new Promise(r => setTimeout(r, 1));
count += amount;
log.push('inc:' + count);
return count;
};
const decrement = async (amount) => {
await new Promise... | const results = [];
for (const [op, val] of ops) {
if (op === 'inc') results.push(await increment(val));
else if (op === 'dec') results.push(await decrement(val));
}
return { results, log: [...log] };
};
return { increment, decrement, batch, getCount: () ... | const assert = require('assert');
async function testCounter() {
const c = createAsyncCounter();
const r1 = await c.increment(5);
assert.strictEqual(r1, 5);
const r2 = await c.decrement(2);
assert.strictEqual(r2, 3);
const c2 = createAsyncCounter();
const { results, log } = await c2.batch(... | async function testCounterAssertions() {
const c = createAsyncCounter();
const { results } = await c.batch([['inc', 1], ['inc', 1], ['inc', 1]]);
assert.deepStrictEqual(results, [1, 2, 3]);
assert.strictEqual(c.getCount(), 3);
const c2 = createAsyncCounter();
const { results: r2, log: l2 } = aw... | syntax_completion |
42 | devbench-syntax-completion | javascript | function* trafficLight() {
let state = 'red';
let ticks = 0;
while (true) {
const command = yield { state, ticks };
ticks++;
switch (state) {
case 'red':
| if (command === 'next') state = 'green';
else if (command === 'emergency') state = 'flashing';
break;
case 'green':
if (command === 'next') state = 'yellow';
else if (command === 'emergency') state = 'flashing';
... | const assert = require('assert');
const light = trafficLight();
let s = light.next();
assert.deepStrictEqual(s.value, { state: 'red', ticks: 0 });
s = light.next('next');
assert.deepStrictEqual(s.value, { state: 'green', ticks: 1 });
s = light.next('next');
assert.deepStrictEqual(s.value, { state: 'yellow', ticks: 2... | // Emergency from red
const l3 = trafficLight();
l3.next();
let s3 = l3.next('emergency');
assert.deepStrictEqual(s3.value, { state: 'flashing', ticks: 1 });
// Staying in flashing until reset
s3 = l3.next('next');
assert.strictEqual(s3.value.state, 'flashing');
s3 = l3.next('next');
assert.strictEqual(s3.value.state,... | syntax_completion |
43 | devbench-syntax-completion | javascript | function mergeConfig(defaults, ...overrides) {
| let result = { ...defaults };
for (const override of overrides) {
result = {
...result,
...override,
metadata: {
...(result.metadata || {}),
...(override.metadata || {}),
mergeCount: ((result.metadata || {}).mergeCount |... | const assert = require('assert');
const defaults = { host: 'localhost', port: 8080, metadata: { version: '1.0', mergeCount: 0 } };
const dev = { port: 3000, debug: true, metadata: { env: 'dev' } };
const local = { host: '0.0.0.0', metadata: { author: 'test' } };
const config = mergeConfig(defaults, dev, local);
asser... | // Single override
const c1 = mergeConfig({ a: 1, metadata: { x: 10, mergeCount: 0 } }, { b: 2 });
assert.strictEqual(c1.a, 1);
assert.strictEqual(c1.b, 2);
assert.strictEqual(c1.metadata.x, 10);
assert.strictEqual(c1.metadata.mergeCount, 1);
// No overrides
const c2 = mergeConfig({ a: 1, metadata: { mergeCount: 0 } }... | syntax_completion |
44 | devbench-syntax-completion | javascript | class AsyncRange {
constructor(start, end, delayMs = 0) {
this.start = start;
this.end = end;
this.delayMs = delayMs;
}
[Symbol.asyncIterator]() {
let current = this.start;
const end = this.end;
const delayMs = this.delayMs;
return {
| async next() {
if (current > end) {
return { value: undefined, done: true };
}
if (delayMs > 0) {
await new Promise(r => setTimeout(r, delayMs));
}
return { value: current++, done: false }... | const assert = require('assert');
async function testAsyncRange() {
const range = new AsyncRange(1, 5);
const values = await collectAsync(range);
assert.deepStrictEqual(values, [1, 2, 3, 4, 5]);
// Empty range
const empty = new AsyncRange(10, 5);
const emptyVals = await collectAsync(empty);
... | async function testAsyncRangeAssertions() {
// Negative range
const neg = new AsyncRange(-2, 2);
assert.deepStrictEqual(await collectAsync(neg), [-2, -1, 0, 1, 2]);
// Large range
const large = new AsyncRange(1, 100);
const largeVals = await collectAsync(large);
assert.strictEqual(largeVals... | syntax_completion |
45 | devbench-syntax-completion | javascript | function fetchUser(id, callback) {
setTimeout(() => {
if (id <= 0) callback(new Error('Invalid user ID'));
else callback(null, { id, name: 'User' + id, roleId: id * 10 });
}, 1);
}
function fetchRole(roleId, callback) {
setTimeout(() => {
if (roleId <= 0) callback(new Error('Invalid... | fetchUser(userId, (err, user) => {
if (err) return callback(err);
fetchRole(user.roleId, (err, role) => {
if (err) return callback(err);
fetchPermissionDetails(role.permissions, (err, details) => {
if (err) return callback(err);
callback(null, ... | const assert = require('assert');
getUserFullProfile(1, (err, profile) => {
assert.strictEqual(err, null);
assert.strictEqual(profile.user, 'User1');
assert.strictEqual(profile.role, 10);
assert.strictEqual(profile.permissions.length, 2);
assert.strictEqual(profile.permissions[0].name, 'read');
... | getUserFullProfile(3, (err, profile) => {
assert.strictEqual(err, null);
assert.strictEqual(profile.user, 'User3');
assert.strictEqual(profile.role, 30);
assert.deepStrictEqual(profile.permissions, [
{ name: 'read', level: 1 },
{ name: 'write', level: 2 }
]);
console.log('Task 45... | syntax_completion |
46 | devbench-syntax-completion | javascript | function initializeSettings(config) {
// Apply defaults using logical assignment operators
// ??= assigns only if null/undefined (NOT for 0, '', false)
// ||= assigns if falsy (0, '', false, null, undefined)
// &&= assigns only if truthy (replaces truthy values)
| config.host ??= 'localhost';
config.port ??= 8080;
config.debug ??= false;
config.retries ||= 3;
config.timeout ||= 5000;
config.verbose &&= config.debug;
config.options ??= {};
config.options.cache ??= true;
config.options.compress ??= false;
config.options.maxSize ||= 1024;
... | const assert = require('assert');
// Test 1: empty config gets all defaults
const c1 = initializeSettings({});
assert.strictEqual(c1.host, 'localhost');
assert.strictEqual(c1.port, 8080);
assert.strictEqual(c1.debug, false);
assert.strictEqual(c1.retries, 3);
assert.strictEqual(c1.timeout, 5000);
assert.strictEqual(c1... | // Nested options with existing values
const c6 = initializeSettings({ options: { cache: false, compress: true, maxSize: 0 } });
assert.strictEqual(c6.options.cache, false); // ??= keeps false
assert.strictEqual(c6.options.compress, true); // ??= keeps true
assert.strictEqual(c6.options.maxSize, 1024); // ||= ove... | syntax_completion |
47 | devbench-syntax-completion | javascript | const Serializable = {
serialize() {
const obj = {};
for (const key of Object.keys(this)) {
obj[key] = this[key];
}
return JSON.stringify(obj);
},
[Symbol.toPrimitive](hint) {
if (hint === 'string') return this.serialize();
return null;
}
};
c... | class Mixed extends Base {
constructor(...args) {
super(...args);
}
}
for (const mixin of mixins) {
Object.getOwnPropertyNames(mixin).forEach(name => {
if (name !== 'constructor') {
Object.defineProperty(Mixed.prototype, name,
... | class BaseModel {
constructor(data) {
Object.assign(this, data);
}
}
class User extends withMixins(BaseModel, Serializable, Validatable) {
static rules = {
name: { required: true, type: 'string' },
age: { required: false, type: 'number' }
};
}
const assert = require('assert');
... | // Test with no mixins
class Plain extends withMixins(BaseModel) {}
const p = new Plain({ x: 1 });
assert.strictEqual(p.x, 1);
assert.strictEqual(typeof p.serialize, 'undefined');
// Test inheritance chain
assert.ok(u instanceof User);
assert.ok(u instanceof BaseModel);
// Test with only Serializable
class OnlySer ex... | syntax_completion |
48 | devbench-syntax-completion | javascript | function processApiResponse(response) {
| const {
status: httpStatus = 200,
data: {
users: [
{ name: primaryName, role: primaryRole = 'user' },
...otherUsers
] = [],
meta: {
page: currentPage = 1,
total: totalPages = 1,
filter... | const assert = require('assert');
// Full response
const r1 = processApiResponse({
status: 200,
data: {
users: [
{ name: 'Alice', role: 'admin' },
{ name: 'Bob', role: 'user' },
{ name: 'Charlie', role: 'user' }
],
meta: {
page: 2,
... | // Custom status
const r3 = processApiResponse({
status: 404,
data: {
users: [{ name: 'X', role: 'mod' }, { name: 'Y' }]
}
});
assert.strictEqual(r3.httpStatus, 404);
assert.strictEqual(r3.primaryName, 'X');
assert.strictEqual(r3.primaryRole, 'mod');
assert.deepStrictEqual(r3.otherUsers, ['Y']);
//... | syntax_completion |
49 | devbench-syntax-completion | javascript | function fetchFromPrimary(id) {
return new Promise((resolve, reject) => {
setTimeout(() => reject(new Error('primary_down')), 10);
});
}
function fetchFromSecondary(id) {
return new Promise((resolve, reject) => {
setTimeout(() => reject(new Error('secondary_timeout')), 20);
});
}
funct... | try {
const result = await Promise.any([
fetchFromPrimary(id),
fetchFromSecondary(id),
fetchFromCache(id)
]);
return { success: true, ...result };
} catch (err) {
if (err instanceof AggregateError) {
const reasons = err.errors.map(e... | const assert = require('assert');
async function testFallback() {
// Cache succeeds (id > 0), primary and secondary fail
const r1 = await fetchWithFallback(42);
assert.strictEqual(r1.success, true);
assert.strictEqual(r1.source, 'cache');
assert.strictEqual(r1.data, 'cached_42');
assert.strictE... | async function testFallbackAssertions() {
// id=0 triggers cache_miss, all fail
const r3 = await fetchWithFallback(0);
assert.strictEqual(r3.success, false);
assert.strictEqual(r3.errorCount, 3);
// id=1 should succeed via cache
const r4 = await fetchWithFallback(1);
assert.strictEqual(r4.s... | syntax_completion |
50 | devbench-syntax-completion | javascript | const _data = new WeakMap();
const TYPE = Symbol('type');
const FORMAT = Symbol('format');
class DynamicRecord {
constructor(fields) {
_data.set(this, {});
this[TYPE] = 'DynamicRecord';
this[FORMAT] = 'json';
for (const [key, value] of Object.entries(fields)) {
this.set(... | set(key, value) {
const data = _data.get(this);
data[key] = value;
Object.defineProperty(this, key, {
get() { return _data.get(this)[key]; },
set(v) { _data.get(this)[key] = v; },
enumerable: true,
configurable: true
});
}
get ... | const assert = require('assert');
const rec = new DynamicRecord({ name: 'test', value: 42 });
// Property access via getter
assert.strictEqual(rec.name, 'test');
assert.strictEqual(rec.value, 42);
// Symbol properties
assert.strictEqual(rec[TYPE], 'DynamicRecord');
assert.strictEqual(rec[FORMAT], 'json');
// Symbol... | // Empty record
const empty = new DynamicRecord({});
assert.strictEqual(+empty, 0);
assert.strictEqual(empty[TYPE], 'DynamicRecord');
assert.deepStrictEqual(empty.toObject(), {});
// Multiple sets
const r2 = new DynamicRecord({});
r2.set('a', 1);
r2.set('b', 2);
r2.set('c', 3);
assert.strictEqual(+r2, 3);
assert.stric... | syntax_completion |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.