add object handling for assertEq
This commit is contained in:
parent
aafe014252
commit
1e03ea78b2
1 changed files with 17 additions and 4 deletions
21
src/index.js
21
src/index.js
|
@ -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)
|
||||
}
|
||||
|
|
Loading…
Add table
Reference in a new issue