add object handling for assertEq

This commit is contained in:
Rowan 2025-03-26 20:52:02 -05:00
parent aafe014252
commit 1e03ea78b2

View file

@ -4,6 +4,19 @@ export class AssertionError extends Error {
}
}
/**
* @template T
* @param {T} obj
* @returns {obj is Exclude<T, Function|symbol|bigint|string|number|boolean|undefined|null|RegExp|Date|Map|Set>}
*/
function isObject(obj) {
return (
obj !== null &&
typeof obj === 'object' &&
[null, Object.prototype].includes(Object.getPrototypeOf(obj))
)
}
export const assert = (value, message = `assertion error: ${value} is not true`) => {
assertEq(value, true, message)
}
@ -11,10 +24,10 @@ export const assert = (value, message = `assertion error: ${value} is not true`)
export const assertEq = (a, b, message = `assertion error: ${a} !== ${b}`) => {
if (a === b) {
return
}
else if (Array.isArray(b) && a.length === b.length) {
b.forEach((n, i) => assertEq(a[i], n))
return
} else if (Array.isArray(b) && a.length === b.length) {
b.forEach((n, i) => assertEq(a[i], n, message))
} else if (isObject(b) && isObject(a)) {
assertEq(JSON.stringify(a), JSON.stringify(b), message)
} else {
throw new AssertionError(message)
}