Skip to content

Unnecessary restrictions or misleading error messages due to relying on truthiness #274

@derekelkins

Description

@derekelkins

The reliance on JavaScript's truthiness leads to many methods failing on valid, if atypical, input. For example, many (probably almost all) places where the code has !options.length leads to unnecessary failure, e.g. string, buffer, wrapped, and more. Of course, this applies to options.lengthInBytes and likely other fields.

As a concrete example, this program fails unnecessarily and misleadingly with "Error: One of length, zeroTerminated, or greedy must be defined for string."

const Parser = require("binary-parser").Parser;
const example = new Parser().string("foo", {length: 0});
const buf = Buffer.from("deadbeef", "hex");
console.log(example.parse(buf));

If you really do want to disallow 0 in these cases (and "" potentially in some others, etc.), then these cases should be checked for explicitly and an error message about 0 being an invalid value produced. Generally, I recommend against ever relying on JavaScript's truthiness. Something like typescript-eslint's strict-boolean-expressions can help with this.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions