Native Assertions

felix felix8a at gmail.com
Mon Jan 14 14:46:41 UTC 2019


mild abuse of tagged templates:

```js
const ENABLE_ASSERT = true;
let a = 3;
let b = 4;
assert `a !== b` `${a} !== ${b}`;
assert `a === b` `${a} === ${b}`;

function assert(strings, ...keys) {
  if (!ENABLE_ASSERT) { return function ignore() {}; }
  let result = eval(String.raw(strings, ...keys))
  if (result) {
    return function pass() {};
  } else {
    return function fail(strings, ...keys) {
      throw new Error("assert fail: " + String.raw(strings, ...keys));
    };
  }
}
```

In theory, the assert code can be completely eliminated if ENABLE_ASSERT is
false.
But Google Closure Compiler only partially eliminates it for some reason.

On Mon, Jan 14, 2019 at 3:37 AM T.J. Crowder <
tj.crowder at farsightsoftware.com> wrote:

> On Sun, Jan 13, 2019 at 6:49 PM Cyril Auburtin
> <cyril.auburtin at gmail.com> wrote:
> >
> > There's `console.assert`
>
> The problem with that and other userland solutions is that for something
> like this:
>
> ```js
> assert(a !== b, `a (${a}) !== b (${b})`);
> ```
>
> you have only three choices for production builds:
>
> 1. Have the asserts active in production (throwing assertion errors).
>
> 2. Have the asserts do the relevant check and process the template
> literal, but not raise an error when it fails. (So `a !== b` still gets
> executed, but no error is raised if it's false.)
>
> 3. Pre-process your scripts to remove the assertions
>
> Whereas with a language-level assert, in production that entire
> pseudo-function-call would be parsed but then completely ignored, including
> the `a !== b` and evaluating the template. And ideally, with a
> language-level feature, even when assertions are enabled, the template
> would only be evaluated if the assertion failed, as though you'd written:
>
> ```js
> if (a !== b) {
>     throw new AssertionError(`a (${a}) !== b (${b})`);
> }
> ```
>
> -- T.J. Crowder
> _______________________________________________
> es-discuss mailing list
> es-discuss at mozilla.org
> https://mail.mozilla.org/listinfo/es-discuss
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.mozilla.org/pipermail/es-discuss/attachments/20190114/58d71a4a/attachment.html>


More information about the es-discuss mailing list