You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

48 lines
1.5 KiB

/*
A stupid thing I wrote so I could have the same assert function in the browser that I
have in Node. This should just be standard in JavaScript.
*/
import { log } from "./logging.js";
/*
This is the error that is thrown when an `assert()` fails.
*/
export class AssertionError extends Error {
/*
This is from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error
which claims you have to do this weird stuff to make your error actually work.
*/
constructor(...params) {
// Pass remaining arguments (including vendor specific ones) to parent constructor
super(...params);
// Maintains proper stack trace for where our error was thrown (only available on V8)
if (Error.captureStackTrace) {
// this "only on V8" is managed by the Error.captureStackTrace test above
Error.captureStackTrace(this, AssertionError);
}
this.name = 'AssertionError';
// Custom debugging information
this.date = new Date();
}
}
/*
If `test` is false then it logs the message and raises the `AssertionError`.
___TODO___: Implement a way to "compile out" these assertions.
+ `test boolean` -- The code only does `if(!test)` so should work with most any falsy thing.
+ `message string` -- The message to log and then attach to the thrown `AssertionError`.
+ ___throws___ `AssertionError(message)`
*/
export const assert = (test, message) => {
if(!test) {
log.assert(test, message);
throw new AssertionError(message);
}
}
export default assert;