Advanced Generics: Higher-Order Functions

by Nov 5, 2023typescript generics

In our journey through TypeScript generics, we’ve covered the basics, interfaces, and classes. Now, it’s time to explore advanced concepts by combining generics with higher-order functions. These functions, which take other functions as arguments or return them, unlock a new level of flexibility and complexity.

Understanding Higher-Order Functions

Higher-order functions are functions that operate on other functions, either by taking functions as arguments or returning them as results. They are a fundamental concept in functional programming and can lead to cleaner, more modular, and more versatile code.

In TypeScript, higher-order functions can be made even more powerful when combined with generics. Let’s see how this works.

Creating a Generic Map Function

One common higher-order function is map, which applies a given function to each element of an array and returns a new array with the results. With generics, we can create a generic map function that works with various data types.

function customMap<T, U>(array: T[], mapper: (item: T) => U): U[] {
  const result: U[] = [];
  for (const item of array) {
    result.push(mapper(item));
  }
  return result;
}

const numbers = [1, 2, 3, 4, 5];
const doubled = customMap(numbers, (num) => num * 2); // Returns [2, 4, 6, 8, 10]

const words = ["apple", "banana", "cherry"];
const lengths = customMap(words, (word) => word.length); // Returns [5, 6, 6]
  • function customMap<T, U>(array: T[], mapper: (item: T) => U): U[] {: This is a higher-order function named customMap. It takes two type parameters, T and U, representing the input and output data types. It also takes two parameters: array, which is an array of type T, and mapper, a callback function that takes an item of type T and returns an item of type U.
  • const result: U[] = [];: Inside the function, an empty array result of type U is created to store the mapped values.
  • for (const item of array) { result.push(mapper(item)); }: This loop iterates over each item in the array. For each item, the mapper function is called to transform it, and the result is pushed into the result array.
  • return result;: The function returns the result array, which now contains the mapped values of type U.

Usage of customMap:

  • const numbers = [1, 2, 3, 4, 5];: An array numbers containing numbers is defined.
  • const doubled = customMap(numbers, (num) => num * 2);: The customMap function is called with numbers as the input array and a callback function (num) => num * 2. This callback function doubles each number in the array. The result is assigned to the doubled variable, which will contain [2, 4, 6, 8, 10].
  • const words = ["apple", "banana", "cherry"];: An array words containing strings is defined.
  • const lengths = customMap(words, (word) => word.length);: The customMap function is called with words as the input array and a callback function (word) => word.length. This callback function returns the length of each word in the array. The result is assigned to the lengths variable, which will contain [5, 6, 6].

In this example, the customMap function is a higher-order function that uses generics to allow mapping of arrays with different data types. It provides flexibility and type safety, and it’s used to perform mapping operations on arrays of numbers and strings.

Applying Generics to Callback Functions

Higher-order functions often take callback functions as arguments. With generics, we can make sure that the callback function’s input and output types align with the higher-order function’s expectations.

function findFirst<T>(array: T[], predicate: (item: T) => boolean): T | undefined {
  for (const item of array) {
    if (predicate(item)) {
      return item;
    }
  }
  return undefined;
}

const numbers = [1, 3, 5, 7, 9];
const isEven = (num: number) => num % 2 === 0;
const firstEven = findFirst(numbers, isEven); // Returns 1

In this example, findFirst is a generic higher-order function that finds the first element in an array that satisfies a given predicate. The predicate callback function ensures that the input matches the array’s data type and the output is a boolean.

Creating a multiplication Skill in Alexa using python

Written By Monisha Macharla

Hi, I'm Monisha. I am a tech blogger and a hobbyist. I am eager to learn and explore tech related stuff! also, I wanted to deliver you the same as much as the simpler way with more informative content. I generally appreciate learning by doing, rather than only learning. Thank you for reading my blog! Happy learning!

RELATED POSTS

Basic Usage of Generics in Typescript

Basic Usage of Generics in Typescript

Keypoints Show how to declare generic functions and classes in TypeScript. Provide examples of generic functions that work with different data types. Demonstrate the use of built-in generics like Array<T> and Promise<T>. Here's the content...

VIDEOS – FOLLOW US ON YOUTUBE

EXPLORE OUR IOT PROJECTS

IoT Smart Gardening System – ESP8266, MQTT, Adafruit IO

Gardening is always a very calming pastime. However, our gardens' plants may not always receive the care they require due to our active lifestyles. What if we could remotely keep an eye on their health and provide them with the attention they require? In this article,...

How to Simulate IoT projects using Cisco Packet Tracer

In this tutorial, let's learn how to simulate the IoT project using the Cisco packet tracer. As an example, we shall build a simple Home Automation project to control and monitor devices. Introduction Firstly, let's quickly look at the overview of the software. Packet...

All you need to know about integrating NodeMCU with Ubidots over MQTT

In this tutorial, let's discuss Integrating NodeMCU and Ubidots IoT platform. As an illustration, we shall interface the DHT11 sensor to monitor temperature and Humidity. Additionally, an led bulb is controlled using the dashboard. Besides, the implementation will be...

All you need to know about integrating NodeMCU with Ubidots over Https

In this tutorial, let's discuss Integrating NodeMCU and Ubidots IoT platform. As an illustration, we shall interface the DHT11 sensor to monitor temperature and Humidity. Additionally, an led bulb is controlled using the dashboard. Besides, the implementation will be...

How to design a Wireless Blind Stick using nRF24L01 Module?

Introduction Let's learn to design a low-cost wireless blind stick using the nRF24L01 transceiver module. So the complete project is divided into the transmitter part and receiver part. Thus, the Transmitter part consists of an Arduino Nano microcontroller, ultrasonic...

Sending Temperature data to ThingSpeak Cloud and Visualize

In this article, we are going to learn “How to send temperature data to ThingSpeak Cloud?”. We can then visualize the temperature data uploaded to ThingSpeak Cloud anywhere in the world. But "What is ThingSpeak?” ThingSpeak is an open-source IoT platform that allows...

Amaze your friend with latest tricks of Raspberry Pi and Firebase

Introduction to our Raspberry Pi and Firebase trick Let me introduce you to the latest trick of Raspberry Pi and Firebase we'll be using to fool them. It begins with a small circuit to connect a temperature sensor and an Infrared sensor with Raspberry Pi. The circuit...

How to implement Machine Learning on IoT based Data?

Introduction The industrial scope for the convergence of the Internet of Things(IoT) and Machine learning(ML) is wide and informative. IoT renders an enormous amount of data from various sensors. On the other hand, ML opens up insight hidden in the acquired data....

Smart Display Board based on IoT and Google Firebase

Introduction In this tutorial, we are going to build a Smart Display Board based on IoT and Google Firebase by using NodeMCU8266 (or you can even use NodeMCU32) and LCD. Generally, in shops, hotels, offices, railway stations, notice/ display boards are used. They are...

Smart Gardening System – GO GREEN Project

Automation of farm activities can transform agricultural domain from being manual into a dynamic field to yield higher production with less human intervention. The project Green is developed to manage farms using modern information and communication technologies....