Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
May 15, 2021 05:03 pm GMT

Functional Programming: Composition of Functions

Input of one function comes from the output of another function.

simple defination of function composition that i could find.

In functiona Programming, Composition takes the place of inheritance in OOP.

composition > inheritance.

it's just better to use composition from the start. It's more flexible, it's more powerful, and it's really easy to do.

Creating a Compose Function

A lot of Javascript FP libraries like ramda, provide pipe() and compose() , which help us in creating composition of functions. Before moving to those,let's create our own example functions.

Here is an example of compose function which take two functions as argument.

let compose = function(fn1, fn2) {return fn2(fn1)}//orlet compose = (fn1,fn2) => fn2(fn1)

Compose Vs Curry

Curry functions are always unary functions which take one argument per application.

Currying functions looks a lot similar pattern to composition, which often causes them to be mistaken for each other.

example of a curry function

const sum = a => b => a + bsum(3)(5) // 8

Are 'Currying' and 'Composition' the same concept in javascript?

No.

First, currying is translating a function that takes multiple arguments into a sequence of functions, each accepting one argument.

here, Notice the distinct way in which a curried function is applied, one argument at a time.

// not curriedconst add = (x,y) => x + y;add(2,3); // => 5// curriedconst add = x => y => x + y;add(2)(3); // => 5

Second, function composition is the combination of two functions into one, that when applied, returns the result of the chained functions.

const compose = f => g => x => f(g(x));compose (x => x * 4) (x => x + 3) (2);// (2 + 3) * 4// => 20

The two concepts are closely related as they play well with one another. Generic function composition works with unary functions (functions that take one argument) and curried functions also only accept one argument (per application).

Function Composition

Function composition is a way of combining pure functions to build more complicated ones. Like the usual composition of functions in mathematics, the result of one function is passed as the argument of the next, and the result of last one is the result of the whole.

Composition is a fancy term which means "combining".

In other words, we can often "combine" multiple steps either into one line of code, or into a new function to contain them

For example, if we want to find the sine of 30 degrees (remember sine uses radians) we could "compose" these two items into the single line: result = sin( degrees_to_radians( 30 ) ). This is the same as in math where we often see f(g(x)).

Example of a compose function which take more than two functions, and applies from left to right manner

We can write a function to compose as many functions as you like. In other words, compose() creates a pipeline of functions with the output of one function connected to the input of the next.

const compose = (...fns) => (x) => fns.reduceRight((y, fn) => fn(y), x);

This version takes any number of functions and returns a function which takes the initial value, and then uses reduceRight() to iterate right-to-left over each function, f, in fns, and apply it in turn to the accumulated value, y. What we're accumulating with the accumulator, y in this function is the return value for the function returned by compose().

Now we can write our composition like this:

const g = n => n + 1;const f = n => n * 2;// replace `x => f(g(x))` with `compose(f, g)`const h = compose(f, g);h(20); //=> 42 

Composition in React

Creating a composition for Different buttons

const Button = props => {  return <button>{props.text}</button>}const SubmitButton = () => {  return <Button text="Submit" />}const LoginButton = () => {  return <Button text="Login" />}

Pass methods as props

A component can focus on tracking a click event, for example, and what actually happens when the click event happens is up to the container component:

const Button = props => {  return <button onClick={props.onClickHandler}>{props.text}</button>}const LoginButton = props => {  return <Button text="Login" onClickHandler={props.onClickHandler} />}const Container = () => {  const onClickHandler = () => {    alert('clicked')  }  return <LoginButton onClickHandler={onClickHandler} />}

Using children

Theprops.childrenproperty allows you to inject components inside other components.

The component needs to outputprops.childrenin its JSX:

const Sidebar = props => {  return <aside>{props.children}</aside>}

and you embed more components into it in a transparent way:

<Sidebar>  <Link title="First link" />  <Link title="Second link" /></Sidebar>

Notice how theAppcomponent doesn't expose the structure of the data.TodoListhas no idea that there islabelorstatusproperties.

The so calledrender proppattern is almost the same except that we use therenderprop and notchildrenfor rendering the todo.

function TodoList({ todos, children }) {  return (    <section className='main-section'>      <ul className='todo-list'>{        todos.map((todo, i) => (          <li key={ i }>{ children(todo) }</li>        ))      }</ul>    </section>  );}function App() {  const todos = [    { label: 'Write tests', status: 'done' },    { label: 'Sent report', status: 'progress' },    { label: 'Answer emails', status: 'done' }  ];  const isCompleted = todo => todo.status === 'done';  return (    <TodoList todos={ todos }>      {        todo => isCompleted(todo) ?          <b>{ todo.label }</b> :          todo.label      }    </TodoList>  );}

Original Link: https://dev.to/pratiksharm/composition-of-functions-178g

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