Skip to content

dizmo/functions-buffered

Repository files navigation

NPM version Build Status Coverage Status

@dizmo/functions-buffered

Returns a buffered and cancelable version for the provided function. The buffered function does not execute before the specified delay passes upon which it executes exactly once, no matter have many times it gets invoked in between.

The cancellation of a particular invocation is only possible while the specified delay has not passed yet. Further, upon the invocation of the buffered function a promise is returned.

Usage

Install

npm install @dizmo/functions-buffered --save

Require

const { buffered } = require("@dizmo/functions-buffered");

Examples

import { buffered } from "@dizmo/functions-buffered";
let fn = buffered((t: Date) => {
    return new Date().getTime() - t.getTime();
}, 200);

fn(new Date()).then((res: number) => {
    console.debug(res);
}).catch((err: Error) => {
    console.error(err);
});
let fn = buffered(() => {
    throw new Error("won't be thrown");
}, 600);

fn().then((res: any) => { // won't execute!
    console.debug(res);
}).catch((err: Error) => {
    console.error(err);
});

fn.cancel();
class Class {
    @buffered.decorator(100)
    public async f1(t: Date): Promise<number> {
        return new Date().getTime() - t.getTime();
    }
    @buffered.decorator // 200ms default
    public async f2(t: Date) {
        return new Date().getTime() - t.getTime();
    }
}

const p1: Promise<number>
    = new Class().f1(new Date());
const p2
    = new Class().f2(new Date());

p1.then((res: number) => { console.debug(res); });
p2.then((res: number) => { console.debug(res); });

Development

Clean

npm run clean

Build

npm run build

without linting and cleaning:

npm run -- build --no-lint --no-clean

with UMD bundling (incl. minimization):

npm run -- build --prepack

with UMD bundling (excl. minimization):

npm run -- build --prepack --no-minify

Lint

npm run lint

with auto-fixing:

npm run -- lint --fix

Test

npm run test

without linting, cleaning and (re-)building:

npm run -- test --no-lint --no-clean --no-build

Cover

npm run cover

without linting, cleaning and (re-)building:

npm run -- cover --no-lint --no-clean --no-build

Documentation

npm run docs

Publish

npm publish

initially (if public):

npm publish --access=public

Copyright

© 2020 dizmo AG, Switzerland