how to use the before function from the underscore library in typescript

To use the before function from underscore.js in TypeScript, we need to install the TypeScript type definition for the library via npm.

npm install @types/underscore
30 chars
2 lines

Then we can import the function from the library and use it in our TypeScript code like this:

index.ts
import { before } from 'underscore';

function showMessage() {
  console.log('Hello world!');
}

const showMessageBefore3Times = before(3, showMessage);
showMessageBefore3Times(); // nothing is logged
showMessageBefore3Times(); // nothing is logged
showMessageBefore3Times(); // 'Hello world!' is logged
showMessageBefore3Times(); // 'Hello world!' is logged
359 chars
12 lines

As you can see, the before function returns a new function that invokes the given function up to a certain number of times, and after that returns the result of the last invocation. In our example, showMessage is invoked only up to 3 times, so the message is only logged twice.

gistlibby LogSnag