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`) => {
|
export const assert = (value, message = `assertion error: ${value} is not true`) => {
|
||||||
assertEq(value, true, message)
|
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}`) => {
|
export const assertEq = (a, b, message = `assertion error: ${a} !== ${b}`) => {
|
||||||
if (a === b) {
|
if (a === b) {
|
||||||
return
|
return
|
||||||
}
|
} else if (Array.isArray(b) && a.length === b.length) {
|
||||||
else if (Array.isArray(b) && a.length === b.length) {
|
b.forEach((n, i) => assertEq(a[i], n, message))
|
||||||
b.forEach((n, i) => assertEq(a[i], n))
|
} else if (isObject(b) && isObject(a)) {
|
||||||
return
|
assertEq(JSON.stringify(a), JSON.stringify(b), message)
|
||||||
} else {
|
} else {
|
||||||
throw new AssertionError(message)
|
throw new AssertionError(message)
|
||||||
}
|
}
|
||||||
|
|
Loading…
Add table
Reference in a new issue