How to use Functional Approach In Typescript

In this approach, we leverage TypeScript’s functional programming capabilities to create self-referencing objects. We define a function to recursively construct the nodes of the linked list, forming the self-referencing structure.

Syntax:

type LinkedListNode = {
  data: string;
  next?: LinkedListNode;
};

const createNode = (data: string, next?: LinkedListNode): LinkedListNode => ({
  data,
  next,
});

const constructLinkedList = (dataArray: string[]): LinkedListNode | undefined => {
  if (dataArray.length === 0) return;
  const [firstData, ...restData] = dataArray;
  return createNode(firstData, constructLinkedList(restData));
};

Example: In this example we defines a LinkedListNode type for a linked list, creates nodes, and constructs a linked list from an array, logging it.

JavaScript
type LinkedListNode = {
    data: string;
    next?: LinkedListNode;
};

const createNode = (data: string, next?: LinkedListNode): LinkedListNode => ({
    data,
    next,
});

const constructLinkedList = (dataArray: string[]): LinkedListNode | undefined => {
    if (dataArray.length === 0) return;
    const [firstData, ...restData] = dataArray;
    return createNode(firstData, constructLinkedList(restData));
};


const linkedList = constructLinkedList(["Geeks", "for", "Geeks"]);
console.log(linkedList);

Output:

{
  "data": "Geeks",
  "next": {
    "data": "for",
    "next": {
      "data": "Geeks",
      "next": undefined
    }
  }
} 


How to Create Self-Referencing Objects in TypeScript ?

In TypeScript, self-referencing objects are mainly objects that have a relationship between the elements and the data structure. We can consider this as the Linked List Data Structure.

We can define the interface or the classes with the properties that may reference instances of the same type.

Table of Content

  • Using Interface
  • Using Class
  • Using Functional Approach

Similar Reads

Using Interface

In this approach, we are going to use a TypeScript interface named node to define the structure of a self-referencing object. Each instance of the interface represents a node with a data property and an optional next property referencing another node....

Using Class

In this approach, we are using a TypeScript class named “node” to define a node structure for a linked list (self-referencing). The class includes a constructor to initialize the “data” and “next” properties, allows the creation of interconnected nodes, and the instantiation of instances forms a linked list....

Using Functional Approach

In this approach, we leverage TypeScript’s functional programming capabilities to create self-referencing objects. We define a function to recursively construct the nodes of the linked list, forming the self-referencing structure....