Skip to content

Instantly share code, notes, and snippets.

@tadeaspetak
Created July 2, 2021 09:06
Show Gist options
  • Save tadeaspetak/433b655f940d995cfa63a42d04b2c8c9 to your computer and use it in GitHub Desktop.
Save tadeaspetak/433b655f940d995cfa63a42d04b2c8c9 to your computer and use it in GitHub Desktop.
Simple assert equals, practical where a testing framework would be an overkill.
function isEquivalent<T>(received: T, expected: T) {
return received && expected && typeof received === "object"
? isValueEquivalent(received, expected)
: received === expected;
}
function isValueEquivalent(a: Record<string, any>, b: Record<string, any>) {
const aPropertyNames = Object.getOwnPropertyNames(a);
const bPropertyNames = Object.getOwnPropertyNames(b);
if (aPropertyNames.length != bPropertyNames.length) return false;
for (const propName of aPropertyNames) {
if (!isEquivalent(a[propName], b[propName])) return false;
}
return true;
}
function assertEqual<T>(received: T, expected: T, id: string) {
if (!isEquivalent(received, expected)) {
throw new Error(`Expected ${JSON.stringify(expected)} but received ${JSON.stringify(received)} at ${id}.`);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment