What is the advantage of using a composition?

I am learning to use Ramda and came across an essay. But I can not understand the purpose of this.

let value = R.compose( calledThird, calledSecond, calledFirst('hello') );

// vs

let value = calledThird( calledSecond( calledFirst('hello') ) );

Is it purely to allow curry? May be,...

let curried = R.compose( calledThird, calledSecond, calledFirst );

curried('hello');

Is there any other purpose?

+4
source share
2 answers

Your second example is precisely its reason, although in reality it has nothing to do with currying.

The functional composition allows you to create more complex functions from simpler ones.

Imagine that you have some type of data that you need to sort, say, a set of meetings. Given that you already have a function sortByDateand a function reverse, you can write sortByDateDescendinghow

var sortByDateDescending = function(appointments) {
    return reverse(sortByDate(appointments));
}

or in ES6:

const sortByDateDescending = appointments => reverse(sortByDate(appointments));

. compose, :

var sortByDateDescending = compose(reverse, sortByDate);

, , , , pre-es6.

, , . ; , , , , .

, , : , .

, , , , compose. Haskell

sortByDateDescending = reverse . sortByDate

Javascript . , , , compose ( , pipe.)

My Ramda .


, , . , . . , .

+10

- .

, , :

var list = [3, 4, 1, 2];

list = filterOutEvens(list);
list = sort(list);
list = prependFoo(list);

- :

[3, 4, 1, 2].filterOutEvens().sort().prependFoo();

, , , Array.prototype, -.

R.compose (, ):

var processList = R.compose(prependFoo, sort, filterOutEvens);
processList([3, 4, 1, 2]);

, :

function filterOutEvens(list) {
    return list.filter(function(item) {
        return item % 2 !== 0;
    });
}

function sort(list) {
    // More cleanly use R.sort here instead of native Array.prototype.sort, which operates in-place.
    var diff = function(a, b) { return a - b; };
    return R.sort(diff, list);
}

function prependFoo(list) {
    return list.map(function(item) {
        return 'foo-' + item;
    });
}

var processList = R.compose(prependFoo, sort, filterOutEvens);

var result = processList([3, 4, 1, 2]);
// -> ["foo-1", "foo-3"]

// Display Stackoverflow snippet output.
document.body.innerHTML = JSON.stringify(result, null, 2);
<script src="//cdn.jsdelivr.net/ramda/0.19.1/ramda.min.js"></script>
+1

Source: https://habr.com/ru/post/1624968/


All Articles