| type RSwitch = { | ||
| [key: string]: any; | ||
| } | [string, any][]; | ||
| type Options = { | ||
| callFn?: boolean; | ||
| }; | ||
| declare function rswitch<T = any>(rcase: string | number | undefined | null, rs: RSwitch, options?: Options): T | undefined; | ||
| declare function rswitchAsync<T = any>(rcase: string | number | undefined | null, rs: RSwitch, options?: Options): Promise<T | undefined>; | ||
| export { rswitch as default, rswitch, rswitchAsync }; |
| "use strict";var s=Object.defineProperty;var o=Object.getOwnPropertyDescriptor;var d=Object.getOwnPropertyNames;var p=Object.prototype.hasOwnProperty;var g=(n,t)=>{for(var e in t)s(n,e,{get:t[e],enumerable:!0})},w=(n,t,e,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of d(t))!p.call(n,i)&&i!==e&&s(n,i,{get:()=>t[i],enumerable:!(r=o(t,i))||r.enumerable});return n};var m=n=>w(s({},"__esModule",{value:!0}),n);var A={};g(A,{default:()=>S,rswitch:()=>a,rswitchAsync:()=>O});module.exports=m(A);function a(n,t,e){let r;for(let[i,u]of Array.isArray(t)?t:Object.entries(t)){if(i.includes(",")&&i.split(",").map(f=>f.trim()).includes(String(n))||i===String(n))return c(u,e);i===""&&(r=c(u,e))}return r}function c(n,t){let{callFn:e=!0}=t||{};return typeof n=="function"&&e?n():n}async function O(n,t,e){let r;for(let[i,u]of Array.isArray(t)?t:Object.entries(t)){if(i.includes(",")&&i.split(",").map(f=>f.trim()).includes(String(n)))return await l(u,e);if(i===String(n))return await l(u,e);i===""&&(r=await l(u,e))}return r}async function l(n,t){let{callFn:e=!0}=t||{};return typeof n=="function"&&e?await n():n}var S=a;0&&(module.exports={rswitch,rswitchAsync}); |
| function a(n,t,e){let u;for(let[i,r]of Array.isArray(t)?t:Object.entries(t)){if(i.includes(",")&&i.split(",").map(f=>f.trim()).includes(String(n))||i===String(n))return s(r,e);i===""&&(u=s(r,e))}return u}function s(n,t){let{callFn:e=!0}=t||{};return typeof n=="function"&&e?n():n}async function d(n,t,e){let u;for(let[i,r]of Array.isArray(t)?t:Object.entries(t)){if(i.includes(",")&&i.split(",").map(f=>f.trim()).includes(String(n)))return await c(r,e);if(i===String(n))return await c(r,e);i===""&&(u=await c(r,e))}return u}async function c(n,t){let{callFn:e=!0}=t||{};return typeof n=="function"&&e?await n():n}var p=a;export{p as default,a as rswitch,d as rswitchAsync}; |
+144
| # rswitch | ||
| The `rswitch` library provides a flexible and compact way to implement switch-like functionality in TypeScript. It allows you to define cases and their corresponding actions using object literals or arrays. This version includes both **synchronous** and **asynchronous** handling of cases and actions. | ||
| ## Installation | ||
| To install the `rswitch` library, use the following npm command: | ||
| ```bash | ||
| npm install rswitch | ||
| ``` | ||
| ## Usage | ||
| The `rswitch` function evaluates a given key against predefined cases and returns the corresponding action. There are two versions of this function available: | ||
| 1. **Synchronous version**: `rswitch` – works for synchronous operations. | ||
| 2. **Asynchronous version**: `rswitchAsync` – works for cases where the action is asynchronous (i.e., it returns a `Promise`). | ||
| ### Syntax | ||
| ```typescript | ||
| rswitch(key: string | number | undefined | null, casesObj: RSwitch, options?: Options): T | undefined; | ||
| rswitchAsync(key: string | number | undefined | null, casesObj: RSwitch, options?: Options): Promise<T | undefined>; | ||
| ``` | ||
| - **`key`**: The value to evaluate against the cases (can be a string, number, `undefined`, or `null`). | ||
| - **`casesObj`**: An object or an array of key-value pairs defining the cases and their corresponding actions. | ||
| - **`options`** _(optional)_: Configuration options to customize the behavior of the `rswitch` function. | ||
| - **`callFn`** _(optional, default: `true`)_: If set to `true`, the function will call actions that are functions and return their result. If set to `false`, the function will return the function itself without calling it. | ||
| ### Example Usage | ||
| #### Synchronous `rswitch` Example | ||
| ```typescript | ||
| import rswitch from "rswitch"; | ||
| // Example usage of rswitch (synchronous) | ||
| const result = rswitch("dev", { | ||
| designer: "Designer", | ||
| "dev, web": "Developer", | ||
| "": "No match found", // Default case | ||
| }); | ||
| console.log(result); // Output: "Developer" | ||
| ``` | ||
| #### Asynchronous `rswitchAsync` Example | ||
| ```typescript | ||
| import { rswitchAsync } from "rswitch"; | ||
| // Example usage of rswitchAsync (asynchronous) | ||
| async function testAsyncSwitch() { | ||
| const result = await rswitchAsync("web", { | ||
| "dev, web": async () => { | ||
| return "Developer"; // Async case | ||
| }, | ||
| designer: "Designer", | ||
| "": "No match found", // Default case | ||
| }); | ||
| console.log(result); // Output: "Developer" (async case) | ||
| } | ||
| testAsyncSwitch(); | ||
| ``` | ||
| ### Case Definitions | ||
| Cases are defined as key-value pairs within the `casesObj`. Here’s how you can define various cases: | ||
| - **Single Case**: Use a direct key-value pair for a single match. | ||
| ```typescript | ||
| { 'dev': 'Developer' } | ||
| ``` | ||
| - **Multiple Cases**: You can group several cases together in one key, separated by commas (`,`), and the key will match any of those cases. | ||
| ```typescript | ||
| { 'dev, web': 'Developer' } | ||
| ``` | ||
| - **Default Case**: The empty string key (`""`) can be used for the default case, which is executed when no other key matches. | ||
| ```typescript | ||
| { '': 'No match found' } | ||
| ``` | ||
| ### Actions | ||
| Actions can be: | ||
| - **Primitive values** (e.g., strings, numbers, booleans). | ||
| - **Functions**: If the action is a function, it will be executed. If the function returns a `Promise`, it will be awaited. | ||
| #### Function Actions: | ||
| If the action is a function: | ||
| - **Synchronous**: The function will be called and its result will be returned. | ||
| - **Asynchronous**: The function will return a `Promise`, which will be resolved before returning the result. | ||
| If `options.callFn` is set to `false`, the function will **not** be invoked, and the function itself will be returned. | ||
| ### Handling Undefined or Null Keys | ||
| If `rcase` is `undefined` or `null`, and no default case (`""`) is defined in `casesObj`, the function will return `undefined`. If a default case is defined, it will return the value of the default case. | ||
| ### Full Example with Multiple Cases | ||
| ```typescript | ||
| import rswitch, { rswitchAsync } from "rswitch"; | ||
| const result = rswitch("web", { | ||
| "dev, web": "Developer", | ||
| designer: "Designer", | ||
| "": "No match found", // Default case | ||
| }); | ||
| console.log(result); // Output: "Developer" | ||
| const result = await rswitchAsync("web", { | ||
| "dev, web": async () => { | ||
| return "Developer"; // Async case | ||
| }, | ||
| designer: "Designer", | ||
| "": "No match found", // Default case | ||
| }); | ||
| console.log(result); // Output: "Developer" (async case) | ||
| ``` | ||
| ### Notes | ||
| - **Multiple Cases for One Action**: You can define one action for multiple cases by separating the case names with commas in a string, like `'dev, web'`. | ||
| - **Default Case**: The `""` key is treated as the default case, executed when no other match is found. | ||
| - **Type Safety**: TypeScript will provide type safety when using `rswitch`, ensuring that the provided `key`, `casesObj`, and `options` match expected types. | ||
| ## Contributing | ||
| We welcome contributions to the `rswitch` library! If you find any issues or want to add new features, please fork the repository and submit a pull request. |
+6
-4
| type RSwitch = { | ||
| [key: string]: any; | ||
| }; | ||
| } | [string, any][]; | ||
| type Options = { | ||
| returnFn?: boolean; | ||
| callFn?: boolean; | ||
| }; | ||
| export declare function rswitch<T = any>(rcase: string | number | undefined | null, rs: RSwitch, options?: Options): T | undefined; | ||
| export default rswitch; | ||
| declare function rswitch<T = any>(rcase: string | number | undefined | null, rs: RSwitch, options?: Options): T | undefined; | ||
| declare function rswitchAsync<T = any>(rcase: string | number | undefined | null, rs: RSwitch, options?: Options): Promise<T | undefined>; | ||
| export { rswitch as default, rswitch, rswitchAsync }; |
+38
-15
| { | ||
| "name": "rswitch", | ||
| "description": "The rswitch library provides a compact and flexible way to implement switch-like functionality in JavaScript. It allows you to define cases and their corresponding actions using an object literal syntax.", | ||
| "version": "0.7.0", | ||
| "version": "0.8.0", | ||
| "author": "Rashed Iqbal", | ||
@@ -9,14 +9,16 @@ "files": [ | ||
| ], | ||
| "main": "./dist/index.js", | ||
| "module": "./dist/index.mjs", | ||
| "types": "./dist/index.d.ts", | ||
| "exports": { | ||
| ".": { | ||
| "types": "./dist/index.d.ts", | ||
| "import": "./dist/rswitch.es.js", | ||
| "require": "./dist/rswitch.umd.js" | ||
| "import": "./dist/index.mjs", | ||
| "require": "./dist/index.js", | ||
| "default": "./dist/index.js" | ||
| } | ||
| }, | ||
| "main": "./dist/rswitch.umd.js", | ||
| "module": "./dist/rswitch.es.js", | ||
| "types": "./dist/index.d.ts", | ||
| "scripts": { | ||
| "build": "tsc && vite build", | ||
| "build": "tsup", | ||
| "lint": "eslint .", | ||
| "test": "jest --verbose false" | ||
@@ -36,3 +38,20 @@ }, | ||
| "node", | ||
| "typescript" | ||
| "typescript", | ||
| "functional programming", | ||
| "decision making", | ||
| "pattern matching", | ||
| "programming utility", | ||
| "asynchronous", | ||
| "async", | ||
| "promise", | ||
| "callback", | ||
| "case statements", | ||
| "switch statement", | ||
| "js", | ||
| "ts", | ||
| "custom switch", | ||
| "dynamic switch", | ||
| "typescript library", | ||
| "helper function", | ||
| "custom conditional logic" | ||
| ], | ||
@@ -45,11 +64,15 @@ "bugs": { | ||
| "devDependencies": { | ||
| "@types/jest": "^29.5.12", | ||
| "@types/node": "^20.4.5", | ||
| "@eslint/js": "^9.26.0", | ||
| "@types/jest": "^29.5.14", | ||
| "eslint": "^9.26.0", | ||
| "eslint-config-prettier": "^10.1.5", | ||
| "eslint-plugin-prettier": "^5.4.0", | ||
| "globals": "^16.1.0", | ||
| "jest": "^29.7.0", | ||
| "ts-jest": "^29.1.2", | ||
| "typescript": "^5.0.2", | ||
| "vite": "^4.4.5", | ||
| "vite-plugin-dts": "^3.4.0", | ||
| "vite-tsconfig-paths": "^4.2.0" | ||
| "prettier": "^3.5.3", | ||
| "ts-jest": "^29.3.2", | ||
| "tsup": "^8.4.0", | ||
| "typescript": "^5.8.3", | ||
| "typescript-eslint": "^8.32.0" | ||
| } | ||
| } |
| function l(r, t, n) { | ||
| for (const [e, i] of Array.isArray(t) ? t : Object.entries(t)) | ||
| if (e.includes(",") && e.split(",").map((u) => u.trim()).includes(String(r)) || e === String(r) || e === "") | ||
| return f(i, n); | ||
| } | ||
| function f(r, t) { | ||
| const n = (t == null ? void 0 : t.returnFn) || !1; | ||
| return typeof r == "function" ? n ? r : r() : r; | ||
| } | ||
| export { | ||
| l as default, | ||
| l as rswitch | ||
| }; |
| (function(e,i){typeof exports=="object"&&typeof module<"u"?i(exports):typeof define=="function"&&define.amd?define(["exports"],i):(e=typeof globalThis<"u"?globalThis:e||self,i(e.rswitch={}))})(this,function(e){"use strict";function i(t,n,r){for(const[f,c]of Array.isArray(n)?n:Object.entries(n))if(f.includes(",")&&f.split(",").map(d=>d.trim()).includes(String(t))||f===String(t)||f==="")return u(c,r)}function u(t,n){const r=(n==null?void 0:n.returnFn)||!1;return typeof t=="function"?r?t:t():t}e.default=i,e.rswitch=i,Object.defineProperties(e,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}})}); |
-71
| # rswitch | ||
| The `rswitch` library provides a compact and flexible way to implement a switch-like functionality in TypeScript. It allows you to define cases and their corresponding actions using an object literal syntax. | ||
| ## Installation | ||
| Install the `rswitch` library using npm: | ||
| ```bash | ||
| npm install rswitch | ||
| ``` | ||
| ## Usage | ||
| The `rswitch` function takes a key and an object containing cases and actions. It evaluates the key against the cases and returns the corresponding action. | ||
| ### Syntax | ||
| ```javascript | ||
| rswitch(key, casesObj, options); | ||
| ``` | ||
| - `key` : The value to evaluate against the cases. | ||
| - `casesObj` : An object containing cases and their actions. | ||
| - `options` : (Optional) An object to customize the behavior of the rswitch function. | ||
| - `returnFn` (optional, default: false): If set to `false`, the `rswitch` function will call actions that are functions and return their values. If set to `true`, the function will return the functions as is. | ||
| ### Example | ||
| ```javascript | ||
| import rswitch from "rswitch"; | ||
| // const {rswitch} = require("rswitch") // commonjs | ||
| const result = rswitch( | ||
| "dev", | ||
| { | ||
| designer: "Designer", | ||
| "dev, web": "Developer", | ||
| "": () => { | ||
| console.log("Hello"); | ||
| }, | ||
| }, | ||
| { | ||
| returnFn: true, | ||
| } | ||
| ); | ||
| console.log(result); | ||
| // Output: Developer | ||
| ``` | ||
| In this example, the `rswitch` function evaluates the key `'dev'` against the cases defined in `casesObj`. Since it matches the case `'dev, web'`, the corresponding action `'Developer'` is returned and assigned to the `result` variable. Finally, the value of `result` is logged to the console. | ||
| ### Case Definitions | ||
| Cases are defined as key-value pairs in the `casesObj` object. | ||
| - Single Case: `{ caseKey: action }` | ||
| - Multiple Cases: `{ 'case1, case2, case3': action }` | ||
| - Default Case: `{ '': action }` | ||
| > Actions can be any value or a function that returns a value. If the action is a function, and the `options` object has `returnFn` set to `false`, it is called, and the returned value is returned. | ||
| If no cases match the evaluated key, the `rswitch` function checks for a default case. If a default case is defined, its corresponding action is performed. If no default case is defined or its action is not provided, `undefined` is returned. | ||
| <br/> | ||
| If you'd like to contribute, please do submit a pull request. | ||
| In case you want support my work | ||
| [](https://buymeacoffee.com/rashed.iqbal) |
Minified code
QualityThis package contains minified code. This may be harmless in some cases where minified code is included in packaged libraries, however packages on npm should not minify code.
Found 1 instance in 1 package
Minified code
QualityThis package contains minified code. This may be harmless in some cases where minified code is included in packaged libraries, however packages on npm should not minify code.
Found 1 instance in 1 package
9694
87.43%6
20%145
101.39%12
50%17
-29.17%3
50%