In functional programming there is such a thing as purity of functions and composition. During calculations inside functions, the values ​​of the variables of the external world do not change. We perform calculations in one function, and the result is passed on to another function. In javascript, you can take as an example:

[].map().reduce(); 

They are all connected by the essence of Array. The processed array values ​​are transferred from the map () functor to reduce (). I would like to know how to write such functions? How are they arranged inside, how is the composition carried out in them (“gluing” through a point)?

UPDATE

Approximately such a principle?

 var Test = function() { var map = function() { console.log('map'); return new Test(); }; var reduce = function() { console.log('reduce'); return new Test(); }; return { map : map, reduce : reduce }; }; var test = new Test(); test.map().reduce() // map // reduce 

Or somehow still different?

  • one
    there is no function composition: there is just an object that has a set of functions, and these functions simply return an object of the same type - Grundy
  • @Grundy thanks. updated the question. Did you mean that? - Matvey Safronov
  • one
    Yes, the implementation is not quite, it is better to blow up the function in the prototype and remove the return from Test - and for the rest it is this - Grundy
  • one
    @MatveySafronov look at the sources of the same Immutable github.com/facebook/immutable-js/blob/master/src everything should be clear, for example, the Map method - Vasily Barbashev
  • @ VasilyBarbashev uhh thank you very much! I was really looking for something like this - Matvey Safronov

1 answer 1

I would like to know how to write such functions?

The function simply has to return some value.

How are they arranged inside, how is the composition carried out in them (“gluing” through a point)?

In the function itself there is no such thing; gluing through a point is a language construct (a dot operator with left associativity).

  • I guess I'll say garbage - but isn't the point really only used to access the fields of the object? Or is it called the operator point with left associativity? - Vladimir Gamalyan
  • @VladimirGamalian is things perpendicular. The operator and its individual properties say little about what the operator does. Yes, that's him. - D-side
  • @VladimirGamalian The function is the object method. At the same time, the function itself is an object and can also have its own properties and methods. - user208916
  • Previously, just in C ++ I heard that the dot is an operator, in js for the first time. - Vladimir Gamalyan