Method chaining & create a custom method chaining!
Published: 2021-06-04 16:28:01

## Function Chainging
        A common syntax for invoking mutiple method calls

> ### __*What ?*__

__Function Chaining__ is a pattern in JavaScript where **multiple functions** are called on the **same object consecutively.** 

We can understand the above definition with examples below. 

### Examples
#### 1
```javascript 
const totalExpensesInINR = tripExpenses
                            .filter(expense => expense.paid)
                            .map(expense => {
                                if (expense.currency === 'USD') return expense.amount * 70;
                                else return expense.amount;
                            })
                            .reduce((amountA, amountB) => amountA + amountB, 0);

```
Here the tripExpenses is an array of objects(_expense_), thus we can apply **filter** which is an array method and it returns array (_find more about [filter](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter)_). Since filter return an array again we can call **map** which is an array method(_find more about [map](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map)_) and so on the get the total of the expense in INR.

> Here we call **filer**, **map** and **reduce** (*multiple methods*) on **tripExpenses** (*same object*) **one after the other** (*consecutively*) to get the require results.

#### 2
```javascript
const numbers = [2, 3, 5, 10];

const newNumbers = numbers
                    .map((number) => number * 2) // [4, 6, 10, 20]
                    .filter((number) => number > 5) // [6, 10, 20]
                    .join("0") // '6010020'
                    .split("") // ['6', '0', '1', '0', '0', '2', '0']
                    .map((ele) => Number(ele));

//[6, 0, 1, 0, 0, 2, 0]

// The object that return on previous method or initial object

```

If you check the above examples we can see that after the **join method** (an array method which returns string). Since the previous method return a string, we can only use a string method to chain further. So we can rewrite the definition of method chaining to

>__Function Chaining__ is a pattern in JavaScript where multiple functions are called on the **inital object for first method and object that returns on previous method for conecutive methods** consecutively. 


> ## __*Why ?*__

## 1. Large number of parameters.
```javascript
function maxParams(param1, param2, param3, ..., paramN) {
    // have some complex logic with params
}

// convert to mathod chaining

maxParamsObj.process1(param1)
            .process2(param2)
            ...
            .processM(paramN)

```

## 2. Reduce to small and reusable unit(function).

## 3. Avoid intermidate variables.

```js 
const persons = [
    {name: 'Akhil', age: 29},
    {name: 'Nikhil', age: 32},
    {name: 'Deepak', age: 21}
]

const personsAgeGraterThan25 = persons.filer(person => person.age > 25);
const personNames = personsAgeGraterThan25.map(person => person.name);
const personNameStr = personNames.join(',')

// This can be done without intermidate variables

const personNameStr = person.filer(person => person.age > 25)
                            .map(person => person.name)
                            .join(',')

```

## 4. Readable and maintainable code.

> ## __*Why Not ?*__

## 1. Confuses the signature.

If a method used in chaining return another object, That make confusion and hard to identify as the code is abstracted.

## 2. Hard to debug.


> ## __*How ?*__

{% codesandbox nervous-rosalind-zoz69 initialpath=/src/service.js %}

Here we created a Recipe class where its has methods like **sliceVegitables**, **addIngredient**, **boil** etc... which return **this** (which is the instance of class itself). Thats why we can call the function with in the class as chain. 
But in the case of **serve** method we are not return anything, So we won't be able to call any Recipe methods after the serve method is executed(we can call only the methods of undefined type).

## Concusions
 * Function Chaining is a pattern in JavaScript where multiple functions are called on the inital object for first method and object that returns on previous method for conecutive methods consecutively.
 * For a custom Method chaining, we always return this from methods, so that we can chain the methods of same class.(If we return anything other than this, then we can only chain with the methods of corresponding type).

keep learning.
# Thanks!