Skip to content

Commit

Permalink
added function postpone
Browse files Browse the repository at this point in the history
  • Loading branch information
daign committed Feb 1, 2019
1 parent a57b884 commit 624bb7d
Show file tree
Hide file tree
Showing 3 changed files with 76 additions and 1 deletion.
22 changes: 22 additions & 0 deletions lib/schedule.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
/**
* Utility mechanisms to manage the time-wise execution of functions.
*/
export abstract class Schedule {
/**
* Gives back a modification of the passed function, that whenever called will only execute after
* a specified time period has elapsed.
* @param callback The function to be modified
* @param wait The waiting time period in milliseconds
* @param context The this-context of the function
* @returns The modified function
*/
public static postpone(
callback: ( ...p: any[] ) => void, wait: number, context: object | null = null
): ( ...q: any[] ) => void {
return ( ...args: any[] ): void => {
setTimeout( (): void => {
callback.apply( context, args );
}, wait );
};
}
}
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"name": "@daign/schedule",
"version": "1.0.0",
"description": "Utilty mechanisms to manage the time-wise execution of functions.",
"description": "Utility mechanisms to manage the time-wise execution of functions.",
"keywords": [
"typescript"
],
Expand Down
53 changes: 53 additions & 0 deletions test/schedule.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
import {expect} from 'chai';

import {Schedule} from '../lib/schedule';

describe( 'Schedule', () => {
describe( 'postpone', () => {
it( 'should call the callback with the passed parameters', ( done: any ) => {
// arrange
const inputs = [ 1, 2, 3 ];
const callback = ( ...args: any[] ): void => {
// assert
expect( args ).to.deep.equal( inputs );
done();
};

// act
const postponedFunction = Schedule.postpone( callback, 40 );
postponedFunction( ...inputs );
} );

it( 'should call with context null if not passed', ( done: any ) => {
// arrange
class TestClass {
public method(): void {
// assert
expect( this ).to.be.null;
done();
}
}
const test = new TestClass();

// act
const postponedFunction = Schedule.postpone( test.method, 40 );
postponedFunction();
} );

it( 'should call with context of test class when passed', ( done: any ) => {
// arrange
class TestClass {
public method(): void {
// assert
expect( this ).to.be.instanceof( TestClass );
done();
}
}
const test = new TestClass();

// act
const postponedFunction = Schedule.postpone( test.method, 40, test );
postponedFunction();
} );
} );
} );

0 comments on commit 624bb7d

Please sign in to comment.