Java has a assert
statement, the JVM disables assertion validation by default. They must be explicitly enabled using command line argument -enableassertions
(or its shorthand -ea
),
while JavaScript supports console.assert()
, it's just a logging method and won't interrupt current procedure if assertion failed.
To bring things together and satisfy various needs, here is a tiny js assertion lib.
globalThis.assert = (()=> {
class AssertionError extends Error {
constructor(message) {
super(message);
this.name = 'AssertionError';
}
}
let config = {
async: true,
silent: false
};
function assert(condition, message = undefined) {
if (!condition) {
if (config.silent) {
//NOOP
} else if (config.async) {
console.assert(condition, message || 'assert');
} else {
throw new AssertionError(message || 'assertion failed');
}
}
}
assert.config = config;
return assert;
})();
/* global assert */
Object.assign(assert.config, {
// silent: true, // to disable assertion validation
async: false, // to validate assertion synchronously (will interrupt if assertion failed, like Java's)
});
let items = [
{id: 1},
{id: 2},
{id: 3}
];
function deleteItem(item) {
let index = items.findIndex((e)=> e.id === item.id);
assert(index > -1, `index should be >=0, the item(id=${item.id}) to be deleted doesn't exist, or was already deleted`);
items.splice(index, 1);
}
console.log('begin');
deleteItem({id: 1});
deleteItem({id: 1});
console.log('end');
_x000D_