JavaScript function Programming-ramdajs

Source: Internet
Author: User

In the JavaScript language world, functions are first class citizens. JavaScript functions are objects that inherit from function, and functions can be used as arguments or return values for another function, which forms the high-order function (or function object) we often call. This constitutes the first element of functional programming. There are a number of functional programming libraries in the JavaScript world that can assist our JavaScript functional experience, the most successful of which are underscore or lodash.

The following Lodash instance code:

var users = [  { ‘user‘: ‘barney‘,  ‘age‘: 36 },  { ‘user‘: ‘fred‘,    ‘age‘: 40 },  { ‘user‘: ‘pebbles‘, ‘age‘: 18 }];var names = _.chain(users)    .pluck(‘user‘)    .join(" , ")    .value();console.log(names);

It is known for its chain-based, lazy evaluation, forming a set of its own DSL style. More programming on Lodash can be found in another blogger's article Lodash the JavaScript tool library.

Functional thinking shows a purely mathematical thinking. A function does not represent any substance (an object, as opposed to an object-oriented idea), but it represents only a conversion behavior for data. A function can be an algorithm sub (function) of an atom, or it can be a combinatorial algorithm sub-composition of multiple atomic algorithms. They are the highest abstraction of behavior, with extraordinary abstraction and expressive power.

Although underscore or lodash also provides the ability to implement function combinations with the . Compose (or . flowright) function, RAMDAJS has a stronger combined force.

Ramdajs is a more functional representation of the JavaScript library, where you can learn more about it http://ramdajs.com/0.17/. Its ability is mainly derived from its own two capabilities: automatic curry and function parameters take precedence over data.

Automatic currying

In computer science, currying is a technique that transforms a function that accepts multiple parameters into a function that takes a single parameter (the first parameter of the original function) and returns a new function that takes the remaining parameters and returns the result. This technique was named by Christopher Strachey, a logic home Curry, although it was invented by Moses Schnfinkel and Gottlob Frege.

In theoretical computer science, Curry provides a way to study functions with multiple parameters in a simple theoretical model, such as a lambda calculus that accepts only a single parameter.

Ramdajs using this technique, the default all API functions support automatic curry. This provides a prerequisite for it to combine another function. If the common map operation needs to accept two parameters, in the RAMDAJS can be implemented in the following two ways:

R.map(function(item){    return item *2; },  [2,3,5]); //输出[4, 6, 10]var map = R.map(function(item){    return item *2;});map([2,3,5]); //输出[4, 6, 10]

If we pass in 2 complete parameters, the R.map function will be executed directly. Otherwise, it will return another function and wait for the parameter to be complete before executing.

For the curry of JavaScript functions, you can also learn more from the blogger's JavaScript function currying http://www.cnblogs.com/whitewolf/p/4495517.html

function parameters take precedence over data

In libraries such as underscore and lodash, it is required to first pass in the data, then the conversion function. In Ramdajs, however, it is a disruptive change. In its statute, the data parameter is the last parameter, and the conversion function and the configuration parameter are better than the data parameters.

Put the conversion function in front, coupled with the function of the automatic curry, you can not touch the data in the case of a function algorithm sub-wrapper into another algorithm, the implementation of two independent conversion function combination.

Let's say we have the following two basic algorithm sub-algorithms:

    1. R.multiply (A, B): Implements a *b; 2:r.map (func, data): A map that implements the collection A–> B.

Because it can be automatically curry, so there is

R.multiply(10, 2); // 20R.multiply(10) (2); // 20

So the example on the face array map can be converted to the following form:

R.map(R.multiply(2)) ([2, 5, 10, 80]); // [4, 10, 20, 160]

The return value of R.map (R.multiply (2)) is also a function, which is a combined conversion function. It combines the map and multiply behavior. It uses the R.map combination to encapsulate the r.multiply (2) Return of the Curry function, which waits for the map function to pass in the corresponding multiplier.

Combination of Ramdajs

With the above two conditions, coupled with the R.compose method provided by Ramdajs, we can easily implement more combinations of algorithms. R.compose is the flow of data that is executed from right to left.

Using the combination of RAMDAJS to achieve the first lodash the same user name splicing example, then we can be divided into 2 algorithm sub-combinations:

    1. R.pluck (prop): Select the object fixed property;
    2. R.join (data): string concatenation of the array.

The code is as follows:

var joinUserName = R.compose(R.join(" , "), R.pluck("user"));joinUserName(users); // "barney , fred , pebbles"

The functional combination here can be expressed as:

If we want the age of the join user, then the following:

var joinUserAge = R.compose(R.join(" , "), R.pluck("age"));joinUserAge(users); // "36 , 40 , 18"

Suppose we want to output not the user age, but the user's birthday, then we can easily combine the previous subtraction algorithm sub:

    1. R.subtract (A, B): Implements the A–b mathematical algorithm.

The code is as follows:

var joinUserBrithDay = R.compose(R.join(","),R.map(R.subtract(new Date().getFullYear())),R.pluck("age"));joinUserBrithDay(users); // "1979,1975,1997"

Again, we want to get the youngest user:

Lodash implementation:

_.chain(users)  .sortBy("age")  .first()  .value();

Ramdajs, you can combine the R.head algorithm sub-r.sortby of the first element and the sorting algorithm:

var youngestUser = R.compose(R.head, R.sortBy(R.prop("age")));youngestUser(users); // Object {user: "pebbles", age: 18}

For example, if we want to get older users, we just need to combine an inverse permutation of the algorithm sub-r.reverse:

var olderUser = R.compose(R.head, R.reverse, R.sortBy(R.prop("age")));olderUser(users); // Object {user: "fred", age: 40}         

I hope you like me as much as RAMDAJS, for more information about it, please see its official website http://ramdajs.com/0.17/.

JavaScript function Programming-ramdajs

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.