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

To use the inject function from the Underscore library in TypeScript, first install the Underscore library using npm:

index.ts
npm install underscore
23 chars
2 lines

Then, import the inject function and use it in your TypeScript code. The inject function is a higher-order function that takes two arguments:

  • A function that represents the method to be applied to each element of the collection
  • A starting value for the reduction
index.ts
import * as _ from "underscore";

const values = [1, 2, 3, 4, 5];

const sum = _.inject(values, (accumulator, value) => accumulator + value, 0);

console.log(sum); // Output: 15
178 chars
8 lines

In the example above, the inject function is used to reduce the values array to a single value representing the sum of all the values. The accumulator argument is used to keep track of the intermediate result while iterating over the values, while the value argument represents the current element of the iteration.

Note that the generic type argument can be used to specify the type of the resulting value:

index.ts
const sum: number = _.inject<number, number>(values, (accumulator, value) => accumulator + value, 0);

console.log(sum); // Output: 15
135 chars
4 lines

gistlibby LogSnag