@devteks/guard-fn
v0.0.2
Published
function guards
Downloads
1
Readme
@devteks/guard-fn
callOnce: Wrapper for a function to be called only once
guarded: execute function guarded with pre function and post function
guardedAsync: execute async function guarded with pre function and post function
guard: guards function with pre function and post function and return same function signature
guardAsync: guards async function with pre function and post function and return same function signature
how to use
npm install @devteks/guard-fn --save
Usage:
import:
const { callOnce, guarded, guardedAsync, guard, guardAsync } = require('@devteks/guard-fn');
// OR
import { callOnce, guarded, guard } from '@devteks/guard-fn';
Using callOnce
const { callOnce } = require('@devteks/guard-fn');
const fn = callOnce((a, b) => {
console.log('called with:', a, b);
return a + b;
});
console.log(fn(1, 2));
// prints `called with: 1 2` and `3`
fn(1, 2); // 3
// prints `3`
fn(1, 2); // 3
// prints `3`
Using guarded
const { guardedAsync } = require('@devteks/guard-fn');
(async () => {
const result = await guardedAsync(
async () => {
await delay(1000);
return 10;
},
() => console.log("before run"),
() => console.log("after run")
);
console.log("result:", result);
// prints after delay for 1 second
// before run
// after run
// result: 10
})();
Using guard
(async () => {
const { guardAsync } = require('@devteks/guard-fn');
const fn = guardAsync(
async (a: number, b: number) => {
await delay(10);
return a + b;
},
() => console.log("before run"),
() => console.log("after run")
);
const result = await fn(1, 2);
console.log("result:", result);
})();