Skip to content

Instantly share code, notes, and snippets.

@another-guy
Last active August 22, 2024 04:42
Show Gist options
  • Save another-guy/adeb27949740a0425cf1a33cee545aec to your computer and use it in GitHub Desktop.
Save another-guy/adeb27949740a0425cf1a33cee545aec to your computer and use it in GitHub Desktop.
coderpad test function
// TS
function test<T extends unknown>(actual: T, expected: T, text?: string): void {
function difference<D>(a: Set<D>, b: Set<D>) {
const arr: D[] = [];
a.forEach(d => arr.push(d));
return new Set<D>(arr.filter(x => !b.has(x)));
}
function same<S extends unknown>(o1: S, o2: S): boolean {
const t1 = typeof o1;
const t2 = typeof o2;
if (t1 === 'bigint' || t2 === 'bigint') throw new Error();
if (t1 === 'function' || t2 === 'function') throw new Error();
if (t1 === 'symbol' || t2 === 'symbol') throw new Error();
if (o2 === undefined && o2 === undefined) return true;
if (o2 === null && o2 === null) return true;
if (t1 === 'undefined' || t2 === 'undefined') throw new Error();
if (
t1 === t2 &&
(
t1 === 'string' ||
t1 === 'number' ||
t1 === 'boolean'
)
)
return o1 === o2;
const o1k = Object.keys(o1 as object);
const o1ks = new Set(o1k);
const o2ks = new Set(Object.keys(o2));
if (
difference(o1ks, o2ks).size > 0 ||
difference(o2ks, o1ks).size > 0
) return false;
return o1k.every(k => same((o1 as any)[k], (o2 as any)[k]));
}
const str = JSON.stringify;
if (same(expected, actual)) console.warn(`[PASS] | ${text}`);
else console.error(`[FAIL] ${text} | Expected ${str(expected)} Actual ${str(actual)}`);
}
// JS
function test(actual, expected, text) {
function difference<D>(a, b) {
const arr = [];
a.forEach(d => arr.push(d));
return new Set(arr.filter(x => !b.has(x)));
}
function same(o1, o2) {
const t1 = typeof o1;
const t2 = typeof o2;
if (t1 === 'bigint' || t2 === 'bigint') throw new Error();
if (t1 === 'function' || t2 === 'function') throw new Error();
if (t1 === 'symbol' || t2 === 'symbol') throw new Error();
if (o2 === undefined && o2 === undefined) return true;
if (o2 === null && o2 === null) return true;
if (t1 === 'undefined' || t2 === 'undefined') throw new Error();
if (
t1 === t2 &&
(
t1 === 'string' ||
t1 === 'number' ||
t1 === 'boolean'
)
)
return o1 === o2;
const o1k = Object.keys(o1);
const o1ks = new Set(o1k);
const o2ks = new Set(Object.keys(o2));
if (
difference(o1ks, o2ks).size > 0 ||
difference(o2ks, o1ks).size > 0
) return false;
return o1k.every(k => same(o1[k], o2[k]));
}
const str = JSON.stringify;
if (same(expected, actual)) console.warn(`[PASS] | ${text}`);
else console.error(`[FAIL] ${text} | Expected ${str(expected)} Actual ${str(actual)}`);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment