Big switch statements get messy fast: lots of case, break, and repeated code.
rswitch is a small library that lets you write the same logic in a cleaner way. You match a value and get the result from an object.
Install
npm i rswitch
Basic idea
You give rswitch:
- a key (the value you want to check)
- a cases object (what to return for each case)
- an optional options object
Simple example
import rswitch from "rswitch";
const role = "dev";
const result = rswitch(role, {
designer: "Designer",
"dev, web": "Freelancer", // match many keys
"": "Unknown", // default case
});
console.log(result); // Freelancer
✅ Tip: "" (empty string) is the default case.
Example 1: Handle status codes (clean and clear)
import rswitch from "rswitch";
function statusMessage(code) {
return rswitch(code, {
"200, 201, 204": "✅ Success",
"400, 401, 403": "⛔ Client error",
"500, 502, 503": "🔥 Server error",
"": "🤷 Unknown status",
});
}
console.log(statusMessage(503)); // 🔥 Server error
No break, no fall-through, easy to read.
Example 2: Run functions as actions
Actions can be values or functions.
import rswitch from "rswitch";
const command = "build";
const result = rswitch(command, {
build: () => "Building...",
test: () => "Testing...",
"": () => "Use: build or test",
});
console.log(result); // Building...
Why rswitch is better than switch (for many cases)
- Short code
- Easy to read
- Group multiple cases like "dev, web"
- Default case is simple: ""
- Works great in JavaScript + TypeScript
If your switch is getting long, rswitch can make it cleaner.
Top comments (0)