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

To use the min function from the underscore library in Typescript, first you need to install the library using npm:

npm install underscore
23 chars
2 lines

Then, you can import the min function and use it in your Typescript code like this:

index.ts
import * as _ from 'underscore';

const numbers = [10, 5, 25, 8, 60];
const smallestNumber = _.min(numbers);

console.log(smallestNumber); // Output: 5
152 chars
7 lines

The min function takes an array of numbers and returns the smallest number in the array. It is a part of the functional programming paradigm that underscore library follows.

Additionally, if you want to use the min function with custom objects, you need to provide a custom iterator function that converts the object into a comparable value. This can be done using generics in Typescript like this:

index.ts
import * as _ from 'underscore';

interface Person {
  name: string;
  age: number;
}

const people: Person[] = [
  { name: 'Alice', age: 22 },
  { name: 'Bob', age: 33 },
  { name: 'Charlie', age: 27 }
];

const youngestPerson = _.min(people, person => person.age);

console.log(youngestPerson); // Output: { name: 'Alice', age: 22 }
335 chars
17 lines

In the above example, the min function takes an array of Person objects, and an iterator function that returns the age of the person. It then returns the person with the smallest age.

gistlibby LogSnag