Javascript functional programming programmer's tool set and javascript tool set

Source: Internet
Author: User

Javascript functional programming programmer's tool set and javascript tool set

If you carefully read the sample code that has appeared so far, you will find that some of the methods here are unfamiliar. They are map (), filter (), and reduce () functions, which are crucial to functional programming in any language. They enable you to write more concise code without using loops and statements.

Map (), filter (), and reduce () functions constitute the core part of the functional programmer tool set. This tool set includes a series of pure and high-level functions, they are the main force of functional methods. In fact, they are typical of pure functions and high-order functions. They use a function as the input and return an output result without any side effects.

However, they are the Implementation Standard of ECMAScript 5.1 in the browser, and they only work in arrays. Each time you call them, a new array is created and returned, and the existing array is not changed. They use functions as input and often use anonymous functions as Callback functions. They traverse the array and apply this function to every element of the array!

myArray = [1,2,3,4];newArray = myArray.map(function(x) {return x*2});console.log(myArray); // Output: [1,2,3,4]console.log(newArray); // Output: [2,4,6,8]

Another point is that they only act on arrays and cannot act on other data structures that can be iterated, such as objects. Don't worry. Many databases, such as Underscore. js, Lazy. js, and stream. js, all implement their own more powerful map (), filter (), and reduce ().

Callback

If you have never used callback before, this concept may confuse you. Especially in Javascript, Javascript provides several methods to declare functions.

Callback functions are used to pass to another function for use. This is a way to pass logic like passing an object:

var myArray = [1,2,3];function myCallback(x){return x+1};console.log(myArray.map(myCallback));

For simple tasks, you can use anonymous functions:

console.log(myArray.map(function(x){return x+1}));

Callback is not only used for functional programming, but can do a lot in Javascript. For example only, this callback () function is used for AJAX calls of jQuery:

function myCallback(xhr) { console.log(xhr.status); return true;}$.ajax(myURI).done(myCallback);

Note that only the name of the function is used here, because we do not want to call the function but pass the function. It is wrong to write it like this:

$. Ajax (myURI). fail (myCallback (xhr); // or $. ajax (myURI). fail (myCallback ());

What happens if we call a function? In this example, myCallback (xhr) will try to execute it. The console will print "undefined" and return true. When ajax () is called, The callback function found by name will be "true", and an error will be reported.

That is to say, we cannot specify the parameters to be passed to the callback function. If our callback function needs to pass ajax () function to the parameter we want, we can put the back function package in an anonymous function:

function myCallback(status) { console.log(status); return true;}$.ajax(myURI).done(function(xhr) { myCallback(xhr.status)});

Array. prototype. map ()

Map () is the boss of these functions. It simply applies callback functions to the elements in the logarithm group.

Syntax: arr. map (callback [, thisArg]);

Parameters:
• Callback (): This function generates an element for the new array. It receives the following parameter: Synchronized currentValue: the element currently traversed by the array.
Sort index: the ordinal number of the current element in the array.
Processed array: the array currently being processed.

• ThisArg: this is an optional parameter. When a callback is executed, it serves as

Example:

Var integers = [1,-0, 9,-8, 3], numbers = [1, 2, 3, 4], str = 'Hello world how ya doing? '; // Map Integers to their own absolute value console. log (integers. map (Math. abs); // multiply the elements in the array by their position ordinal number. log (numbers. map (function (x, I) {return x * I}); // The upper-case console is changed when a word is separated. log (str. split (''). map (function (s, I) {if (I % 2 = 0) return s. toUpperCase (); else return s ;}));

Although the Array. prototype. map method is the standard method for Array objects in Javascript, you can easily extend your own objects.

MyObject.prototype.map = function(f) {  return new MyObject(f(this.value)); }; 

Array. prototype. filter ()

The filter () function filters out some elements in the array. The callback function must return true (retained to the new array) or false (discard ). Map () is used to return the elements you threw away as null. However, the filter () function will delete these elements from the new array, instead of leaving null to occupy the position.

Syntax: arr. filter (callback [, thisArg]);

• Callback (): This function is used to test each element in the array. You must retain the returned truth; otherwise, false is returned. It has these parameters: distinct currentValue: elements currently traversed by the Array
Sort index: the ordinal number of the current element in the array.
Processed array: the array currently being processed.

• ThisArg: this is an optional parameter. When a callback is executed, it serves as

Example:

Var myarray = [1, 2, 3, 4] words = 'Hello 123 world how 345 ya doing '. split (''); re = '[a-zA-Z]'; // filter the integer console. log ([-2,-1, 0, 1, 2]. filter (function (x) {return x> 0}); // filter all letters in the console. log (words. filter (function (s) {return s. match (re) ;})); // randomly removes the element console from the array. log (myarray. filter (function () {return Math. floor (Math. random () * 2 )}));

Array. prototype. reduce ()

The reduce () function, also known as fold, is used to aggregate all values in the array. The callback needs to return the logic of the combined object. Numbers are often added together or multiplied together. For strings, they are often appended together.

Syntax: arr. reduce (callback [, initialValue]);

Parameters
• Callback (): This function combines two objects into one and returns them. Parameters include: Values previousValue: The value returned when the last callback function was called, or the initial value (if any)
Explain currentValue: elements currently being processed by the Array
Sort index: the ordinal number of the current element in the array.
Processed array: the array currently being processed.

• InitialValue: Optional. Initial Value of the input parameter for the first callback

Example

Var numbers = [1, 2, 3, 4]; // adds all values in the array to the console. log ([1, 2, 3, 4, 5]. reduce (function (x, y) {return x + y}, 0); // find the maximum value in the array console. log (numbers. reduce (function (a, B) {return Math. max (a, B) // The max () function can have only two parameters }));

Other functions

Map (), filter (), and reduce () functions are not alone in the toolbox of our auxiliary functions. More functions are used in almost all functional applications.

Array. prototype. forEach

The forEach () function is essentially a non-pure version of the map () function. it traverses the entire array and applies callback to each element. However, these callback functions do not return values. It is a more pure way to implement a for loop.

Syntax: arr. forEach (callback [, thisArg]);

Parameters:
• Callback (): applied to each element in the array. Parameters include: processing currentValue: elements currently being processed in the array
Sort index: the ordinal number of the current element in the array.
Processed array: the array being processed.

• ThisArg: Optional. The value of this in the callback function.

Example:

Var arr = [1, 2, 3]; var nodes = arr. map (function (x) {var elem = document. createElement ("div"); elem. textContent = x; return elem;}); // output the log arr for the value of each element. forEach (function (x) {console. log (x)}); // append the node to the DOM node. forEach (function (x) {document. body. appendChild (x )});

Array. prototype. concat

If you do not use for or while to process arrays, you often need to splice the arrays. Another built-in Javascript function concat is dedicated to this. The concat function returns a new array without changing the old one. It concatenates all the parameters you pass in.
Console. log ([1, 2, 3]. concat (['A', 'B', 'C']) // concatenate two Arrays
// Output: [1, 2, 3, 'A', 'B', 'C']

It returns the arrays spliced by two arrays, and the original arrays are not changed. This means that the concat function can be called in a chain.

var arr1 = [1,2,3];var arr2 = [4,5,6];var arr3 = [7,8,9];var x = arr1.concat(arr2, arr3);var y = arr1.concat(arr2).concat(arr3));var z = arr1.concat(arr2.concat(arr3)));console.log(x);console.log(y);console.log(z);

The values of x, y, and z are [1, 2, 3, 4, 5, 6, 7, 8, 9].

Array. prototype. reverse

This Javascript built-in function is used for array deformation. The reverse function is used to reverse an array, that is, the first element runs to the end, and the last element becomes the first element.

However, this function does not return a new array, but replaces the original array. We can do better. The following is a pure reverse Array Function.

var invert = function(arr) { return arr.map(function(x, i, a) {  return a[a.length - (i + 1)]; });};var q = invert([1, 2, 3, 4]);console.log(q);

Array. prototype. sort

Similar to map (), filter (), and reduce () functions, the sorting function sort () needs to input a callback function to define how arrays are sorted. However, like reverse (), it also replaces the original array. This is not good.
Arr = [200, 12, 56, 7,344];
Console. log (arr. sort (function (a, B) {return a-B }));
// Arr: [7, 12, 56,200,344];

We can write a pure function sort (), but the source code of the sorting algorithm is very troublesome. For a particularly large array, appropriate algorithms should be selected based on the specific data structure, such as fast sorting, Merge Sorting, and Bubble sorting.

Array. prototype. every and Array. prototype. some

Array. prototype. every () and Array. prototype. some () are pure high-level functions. They are Array object methods. The callback function is used to test based on the Boolean values returned by each element of the Array (or equivalent to a Boolean value. If all elements in the array return True through callback function calculation, the every () function returns true. If an element in the array returns True, some () function returns True.

Example:

function isNumber(n) { return !isNaN(parseFloat(n)) && isFinite(n);}console.log([1, 2, 3, 4].every(isNumber)); // Return: trueconsole.log([1, 2, 'a'].every(isNumber)); // Return: falseconsole.log([1, 2, 'a'].some(isNumber)); // Return: true

Related Article

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.