Home > Article > Web Front-end > A brief introduction to Javascript functional programming_javascript skills
For decades, functional programming has been a favorite among computer science enthusiasts, buried in computer labs by data scientists and PhD hopefuls due to its mathematical purity and enigmatic nature. people use. But now, it's experiencing a renaissance, thanks to modern languages like Python, Julia, Ruby, Clojure and - but not the last - Javascript.
You mean Javascript? This WEB scripting language? That’s right!
Javascript has proven to be an important technology that has not disappeared for a long time. This is mainly due to the ability to be reborn due to some of the frameworks and libraries it extends, such as backbone.js, jQuery, Dojo, underscore.js, etc. This is directly related to Javascript's true identity as a functional programming language. An understanding of functional programming in Javascript is important and will be useful to programmers of all levels for quite some time.
Why? Functional programming is very powerful, robust, and elegant. It is very useful and efficient for large data structures. As a client-side scripting language, Javascript is very beneficial for functionally manipulating the DOM, organizing API responses, and completing other tasks when dealing with increasingly complex websites.
In this book, you will learn everything you need to know about functional programming in Javascript: how to build your Javascript web applications with functional programming, how to unlock the hidden power of Javascript, and how to write more powerful code , and because the program is smaller, the code is easier to maintain, can be downloaded faster, and costs less. You'll also learn the core concepts of functional programming and how to apply them to Javascript, how to avoid some problems when using Javascript as a functional language, and how to mix functional programming and object-oriented programming in Javascript.
But before we get started, let’s do an experiment.
Example
Perhaps the best way to introduce functional programming in Javascript is with a quick example. We'll do some tasks in Javascript - one using a traditional, native approach, and another using functional programming. We will then compare these two methods.
Application - an e-commerce website
In order to pursue realism, we will make an e-commerce website, a mail order coffee bean company. This website sells several types of coffee, with different qualities and, of course, different prices.
Imperative method
First, we start writing the program. To make this example practical, we need to create some objects to hold the data. We can get the value from the database if needed. But now we assume they are statically defined:
// create some objects to store the data. var columbian = {  name: 'columbian', basePrice: 5 }; var frenchRoast = { name: 'french roast', basePrice: 8 }; var decaf = { name: 'decaf', basePrice: 6 }; // 我们将使用辅助函数计算价格 // 根据size打印到一个HTML的列表中 function printPrice(coffee, size) { if (size == 'small') { var price = coffee.basePrice + 2; } else if (size == 'medium') { var price = coffee.basePrice + 4; } else { var price = coffee.basePrice + 6; } // create the new html list item var node = document.createElement("li"); var label = coffee.name + ' ' + size; var textnode = document.createTextNode(label+' price: $'+price); node.appendChild(textnode); document.getElementById('products').appendChild(node); } // 现在我们只需根据咖啡的各种价格和size的组合调用printPrice函数 printPrice(columbian, 'small'); printPrice(columbian, 'medium'); printPrice(columbian, 'large'); printPrice(frenchRoast, 'small'); printPrice(frenchRoast, 'medium'); printPrice(frenchRoast, 'large'); printPrice(decaf, 'small'); printPrice(decaf, 'medium'); printPrice(decaf, 'large');
As you can see, this code is very basic. What if there were more types of coffee now than just these three? What if there are 20, or even 50? What if there are more sizes? What if there is organic and inorganic? This will quickly add up to a huge amount of code!
Using this method, we let the machine print every coffee type and every size. This is the basic problem with taking this imperative approach.
Functional Programming
Imperative code tells the computer step by step what needs to be done to solve the problem. In contrast, functional programming pursues describing the problem mathematically and letting the computer do the rest.
In a more functional way, the same application can be written like this:
// 从接口中分解数据和逻辑 var printPrice = function(price, label) { var node = document.createElement("li"); var textnode = document.createTextNode(label+' price: $'+price); node.appendChild(textnode); document.getElementById('products 2').appendChild(node); } // 为每种咖啡创建函数对象 var columbian = function(){ this.name = 'columbian'; this.basePrice = 5; }; var frenchRoast = function(){ this.name = 'french roast'; this.basePrice = 8; }; var decaf = function(){ this.name = 'decaf'; this.basePrice = 6; }; // 为每种size通过字面量创建对象 var small = { getPrice: function(){return this.basePrice + 2}, getLabel: function(){return this.name + ' small'} }; var medium = { getPrice: function(){return this.basePrice + 4}, getLabel: function(){return this.name + ' medium'} }; var large = { getPrice: function(){return this.basePrice + 6}, getLabel: function(){return this.name + ' large'} }; // 将所有咖啡的种类和size放到数组里 var coffeeTypes = [columbian, frenchRoast, decaf]; var coffeeSizes = [small, medium, large]; // 创建由上面内容组成的新对象,并把它们放到一个新数组里 var coffees = coffeeTypes.reduce(function(previous, current) { var newCoffee = coffeeSizes.map(function(mixin) { // `plusmix`是函数式的minxin, 见第7章 var newCoffeeObj = plusMixin(current, mixin); return new newCoffeeObj(); }); return previous.concat(newCoffee); },[]); // 现在我们已经定义了如何获得所有咖啡种类和size组合方式的价格,现在可以直接打印它们了 coffees.forEach(function(coffee){ printPrice(coffee.getPrice(),coffee.getLabel()); });
The first thing that needs to be made clear is that this code is more modular. Now adding a size or adding a coffee type is as simple as the following code:
var peruvian = function(){ this.name = 'peruvian'; this.basePrice = 11; }; var extraLarge = { getPrice: function(){return this.basePrice + 10}, getLabel: function(){return this.name + ' extra large'} }; coffeeTypes.push(Peruvian); coffeeSizes.push(extraLarge);
咖啡对象的数组和size对象的数组混合(mix)到了一起,也就是他们的方法和成员变量被组合到了一块儿 ——通过一个叫“plusMinxin”的自定义函数(详见第七章)。这些咖啡类型的类(columbian, frenchRoast, decaf)包含了成员变量, 而这些size对象(small, medium, large)包含了获取名称和计算价格的方法。 ”混合”(minxing)这个动作通过一个map操作来起作用,也就是对数组中的每一个成员执行一个纯函数并返回一个新的函数, 然后这些返回的函数被放到了一个reduce函数中被操作,reduce也是一个高阶函数,和map有些像, 只是reduce把数组里的所有元素处理后组合到了一个东西里面。最终,新的数组包含了所有可能的种类和size的组合, 这个数组通过forEach方法遍历,forEach也是一个高阶函数,它会让数组里面每一个对象作为参数执行一遍回调函数。 在这个例子里,这个回调函数是一个匿名函数,它获取这些对象后,以对象的getPrice()和getLabel() 两个方法的返回值作为参数调用printPrice函数。
实际上,我们可以让这个例子更加函数式:去掉coffees变量,并将函数串到一起链式调用,这也是函数式编程的一个小技巧。
coffeeTypes.reduce(function(previous, current) { var newCoffee = coffeeSizes.map(function(mixin) { // `plusMixin` function for functional mixins, see Ch.7 var newCoffeeObj = plusMixin(current, mixin); return new newCoffeeObj(); }); return previous.concat(newCoffee); },[]).forEach(function(coffee) { printPrice(coffee.getPrice(),coffee.getLabel()); });
这样,控制流没有像命令式代码那样从头到尾的顺序进行。在函数式编程里,map函数和其它高阶函数代替了for和while循环, 只有少量关键的代码是在顺序执行。 这使得新接触的人在阅读这样范式的代码有些困难,但是一旦你能够欣赏它,你就会发现这根本没啥难的, 而且这样写看起来更好。
这个例子仅仅是刚开始展露Javascript中函数式编程能做什么。通过这本书,你将会看到更多函数式实现的强悍的例子。
总结
首先,采用函数式风格的优点已经明确了。 其次,不要害怕函数式编程。的确,它往往被认为是编程语言的纯逻辑形式,但是我们不需要理解lambda演算也能够在日常任务中应用它。 实际上,通过把我们的程序拆分成小的片段,它们变得更容易被理解、维护,也更加可靠。 map和reduce函数是Javascript中不太被知道的内建函数,然而我们将要关注它们。
Javascript是一个脚本语言,可交互,易使用,不需要编译。我们甚至不需要下载任何开发软件, 你最喜欢的浏览器就可以作为开发环境的解释器。
感兴趣吗?好,我们开始!