Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
March 11, 2021 08:30 am GMT

1. Higher-Order Functions (HOF)

There are two ways of constructing a software design: One way is to make it so simple that there are obviously no deficiencies, and the other way is to make it so complicated that there are no obvious deficiencies. - C.A.R. Hoare, 1980 ACM Turing Award Lecture

A higher-order function is a function that takes a function as an argument or returns a function.

When we were in school we learned algebra formulas like

f.g = f(g(x))

can be translated into JavaScript

const compose = (f, g) => x => f(g(x));

How to write HOF?

const filter = (predicate, xs) => xs.filter(predicate);const isEven = (type) => (x) => Object(x) instanceof type && x % 2 === 0;filter(isEven(Number), [2, "1", 4, null, undefined, 100, "6"]);// [2, 4, 100]

If you see the above code I have created 2 functions filter and isEven. filter function accepts two arguments function and array so we can say that filter function is higher-order function.

So, the predicate is -> isEven(Number) so both are functions (isEven and Number)

xs.filter(predicate)

Equivalent to

xs.filter(isEven(Number))

If you see the definition of isEven function its curry function so you can call curry function like

function_name(argument_1)(argument_2)

So, when xs.filter(predicate) executes its passing array values too in a predicate function like

xs.filter(val=>predicate(val))// orxs.filter(val=>isEven(Number)(val)) 

So, when you pass function and array in the filter function it will filter values based on your predicate function and array values.

I am learning FP. If you feel I am wrong then please feel free to write a comment in the comment box so I will update the document.


Original Link: https://dev.to/ajaykumbhare/1-higher-order-functions-hof-dec

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To