@cursorsdottsx/s

Functional switch blocks for comparing numbers.

Usage no npm install needed!

<script type="module">
  import cursorsdottsxS from 'https://cdn.skypack.dev/@cursorsdottsx/s';
</script>

README

| a | b | c | d | e | f | g | h | i | j | k | l | m | n | o | p | q | r | s | t | u | v | w | x | y | z |

S is for Switch

@cursorsdottsx/s

Functional switch blocks for comparing numbers. Switch was never that good or useful. With this small library, at least it's good with numbers.

Super easy to add and install:

npm install @cursorsdottsx/s
yarn add @cursorsdottsx/s

And also super easy to use:

import Switch from "@cursorsdottsx/s";

After you import the library, it will attach a global function named Switch that's easy to use.

Switch(values, cases)

  • values – An object with the values to compare.
  • cases – All the cases.

Example:

const x = 10;

Switch(
    { x },
    {
        ["x > 5"]() {
            console.log("Greater than 5.");
        },
        ["default"]() {
            console.log("Less than 5.");
        },
    }
);

Switch supports 6 comparators, >, <, >=, <=, =, and !=. It also supports & for joining two comparisons like this:

const x = 10;
const y = 5;

Switch(
    { x, y },
    {
        ["x > 5 & y > 5"]() {
            console.log("Both greater than 5.");
        },
        ["default"]() {
            console.log("One is less than 5.");
        },
    }
);

The default case is optional, and you can have as many cases as you'd like. Only one case gets executed and its return value is Switch's return value.

Each comparison must be in the format identifier comparator value, though this may change in the future.

If there are any features you'd like to add, please either open an issue or pull request!

npm abc's homepage