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

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

npm install underscore
23 chars
2 lines

Import the foldr function from the Underscore library and define the type of the array and accumulator using generics. The first argument is the array, the second argument is the callback function that reduces the array values into a single value, and the third argument is the initial accumulator value:

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

const numbers: number[] = [1, 2, 3, 4, 5];

const sum = foldr<number, number>(numbers, (acc, num) => acc + num, 0);

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

In the above example, the foldr function takes an array of numbers and reduces them into a sum using a callback function (acc, num) => acc + num. The initial accumulator value is 0. The result is stored in the sum variable and printed to the console.

gistlibby LogSnag