0.0.1 • Published 3 years ago
data-switch v0.0.1
🎛️ data-switch
The
switch
statement, but for data, not instructions
Motivation
I don't like writing code like this:
let result;
switch(item) {
case "Alice": result = 123; break;
case "Bob": result = 456; break;
case "Charlie": result = 789; break;
default: result = 0; break;
}
Usage
const dataSwitch = require('data-switch');
const item = "Bob";
const result = dataSwitch(item, {
"Alice": 123,
"Bob": 456,
"Charlie": 789,
"default": 0,
};
// result === 456
NOTE
- The implementation of this module is trivial and most likely buggy. I mostly published it to raise awareness of this technique as such, since I way too often see code like the snippet above (under "Motivation").
- Yes, the same can be achieved with
result = { a: 1, b: 2 }[item];
, but usingdataSwitch
allows for a default and is more readable, in my opinion. Also, it's in the tradition of node micro packages: https://github.com/parro-it/awesome-micro-npm-packages - Internally, this is just an object/key lookup, and keys will be coerced into strings, so be aware of this. The module will allow you to shoot yourself in the foot. Only use Numbers or strings as keys. For boolean values, just use the ternary operator instead of this module. See the examples below for how numbers behave.
- The key "default" is just a string. See below for an alternative version which doesn't rely on this.
More examples
const filterSelector = "Active";
const filterFunction = dataSwitch(filterSelector, {
"All": () => true,
"Active": (todo) => !todo.completed,
"Completed": (todo) => todo.completed,
});
const filteredTodos = todos.filter(filterFunction);
Numbers work mostly as expected:
const item = -0.0;
const result = dataSwitch(item, {
0: 123,
default: 456,
});
// result === 123
const item = 42;
const result = dataSwitch(item, {
42: 123,
default: 456,
});
// result === 123
Alternative version
Use require("data-switch").alternative
to get an alternative version that allows you to use the string "default" as a case:
const dataSwitch = require("data-switch").alternative;
const item = "invalid";
const result = dataSwitch(filterSelector, {
"Bob": 123,
"default": 456,
}, 0);
// result === 0