While predominantly academic in nature, here is a pure JavaScript solution for removing certain functions from your code entirely. This approach may result in the compiled code being optimized away based on the settings of your compiler.
/** @const */
var ENABLE_ASSERTIONS = false; // change to true for debug mode
var assert = (() => ENABLE_ASSERTIONS ? () => {}: test => console.assert(test(), test.toString()))();
If ENABLE_ASSERTIONS == true
, the assert function becomes an empty function: () => {}
. However, if ENABLE_ASSERTIONS == false
, it accepts a function as input, executes that function, and assesses the result.
Usage:
var safeDivision = function (numeratorFunc, denominatorFunc) {
assert(() => denominatorFunc() !== 0);
return numeratorFunc() / denominatorFunc();
}
This approach mimics the behavior of C-style asserts. The function within the assert only executes when ENABLE_ASSERTIONS == false
. By passing a function to assert instead of an expression, we ensure that the expression inside the assert is not evaluated during production code. As a result, an optimizing compiler can potentially eliminate the assert statement as dead code.