1. background

In pursuit of a real-world application, let’s say we need an e-commerce web application
for a mail-order coffee bean company. They sell several types of coffee and in different
quantities, both of which affect the price.

  1. Imperative methods

First, let’s go with the procedural route. To keep this demonstration down to earth, we’ll
have to create objects that hold the data. This allows the ability to fetch the values from a
database if we need to. But for now, we’ll assume they’re 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
};

// we'll use a helper function to calculate the cost
// according to the size and print it to an HTML list
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);
}
// now all we need to do is call the printPrice function
// for every single combination of coffee type and size
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');

 
  1. Functional programming

While imperative code tells the machine, step-by-step, what it needs to do to solve the
problem, functional programming instead seeks to describe the problem mathematically so
that the machine can do the rest.
With a more functional approach, the same application can be written as follows:

// separate the data and logic from the interface
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);
}
// create function objects for each type of coffee
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;
};
// create object literals for the different sizes
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'}
};
// put all the coffee types and sizes into arrays
var coffeeTypes = [columbian, frenchRoast, decaf];
var coffeeSizes = [small, medium, large];
// build new objects that are combinations of the above
// and put them into a new array
var coffees = coffeeTypes.reduce(function(previous, current) {
var newCoffee = coffeeSizes.map(function(mixin) {
// `plusmix` function for functional mixins, see Ch.7
var newCoffeeObj = plusMixin(current, mixin);
return new newCoffeeObj();
});
return previous.concat(newCoffee);
},[]);
// we've now defined how to get the price and label for each
// coffee type and size combination, now we can just print them
coffees.forEach(function(coffee){
printPrice(coffee.getPrice(),coffee.getLabel());
});
The first thing that should be obvious is that it is much more modular. This makes adding
a new size or a new coffee type as simple as shown in the following code snippet:
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);

Arrays of coffee objects and size objects are “mixed” together,—that is, their methods and
member variables are combined—with a custom function called plusMixin (see Chapter
7, Functional and Object-oriented Programming in JavaScript). The coffee type classes
contain the member variables and the sizes contain methods to calculate the name and
price. The “mixing” happens within a map operation, which applies a pure function to each
element in an array and returns a new function inside a reduce() operation—another
higher-order function similar to the map function, except that all the elements in the array
are combined into one. Finally, the new array of all possible combinations of types and
sizes is iterated through with the forEach() method The forEach() method is yet another
higher-order function that applies a callback function to each object in an array. In this
example, we provide it as an anonymous function that instantiates the objects and calls the
printPrice() function with the object’s getPrice() and getLabel() methods as
arguments.
Actually, we could make this example even more functional by removing the coffees
variable and chaining the functions together—another little trick in functional
programming.

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());
});

Also, the control flow is not as top-to-bottom as the imperative code was. In functional
programming, the map() function and other higher-order functions take the place of for
and while loops and very little importance is placed on the order of execution. This makes
it a little trickier for newcomers to the paradigm to read the code but, once you get the
hang of it, it’s not hard at all to follow and you’ll see that it is much better.

 

a primary example for Functional programming in javascript的更多相关文章

  1. JavaScript Functional Programming

    JavaScript Functional Programming JavaScript 函数式编程 anonymous function https://en.wikipedia.org/wiki/ ...

  2. BETTER SUPPORT FOR FUNCTIONAL PROGRAMMING IN ANGULAR 2

    In this blog post I will talk about the changes coming in Angular 2 that will improve its support fo ...

  3. Functional Programming without Lambda - Part 1 Functional Composition

    Functions in Java Prior to the introduction of Lambda Expressions feature in version 8, Java had lon ...

  4. Sth about 函数式编程(Functional Programming)

    今天开会提到了函数式编程,针对不同类型的百年城方式,查阅了一部分资料,展示如下: 编程语言一直到近代,从汇编到C到Java,都是站在计算机的角度,考虑CPU的运行模式和运行效率,以求通过设计一个高效的 ...

  5. Beginning Scala study note(4) Functional Programming in Scala

    1. Functional programming treats computation as the evaluation of mathematical and avoids state and ...

  6. Functional Programming without Lambda - Part 2 Lifting, Functor, Monad

    Lifting Now, let's review map from another perspective. map :: (T -> R) -> [T] -> [R] accep ...

  7. Functional programming

    In computer science, functional programming is a programming paradigm, a style of building the struc ...

  8. Java 中的函数式编程(Functional Programming):Lambda 初识

    Java 8 发布带来的一个主要特性就是对函数式编程的支持. 而 Lambda 表达式就是一个新的并且很重要的一个概念. 它提供了一个简单并且很简洁的编码方式. 首先从几个简单的 Lambda 表达式 ...

  9. Functional programming idiom

    A functional programming function is like a mathematical function, which produces an output that typ ...

随机推荐

  1. HTML5 十大新特性(十)——Web Socket

    webSocket是H5新加的一个协议,为了解决http协议的request.response一一对应和它自身的被动性,以及ajax轮询等问题.一方可以发送多条信息,连接不中断,永久连接,但也导致了服 ...

  2. HTML5 十大新特性(六)——地理定位

    简单地用一句话概括就是,使用js获取浏览器当前所在的地理坐标,实现LBS(Location Based Service,基于定位的服务). 下面写一下它的基本调用: if(navigator.geol ...

  3. js json 特定条件删除 增加 遍历

    <script type="text/javascript">        //直接声明json数据结构         var myJSONObject = [   ...

  4. 【OS】实模式和保护模式区别及寻址方式

    实模式和保护模式区别及寻址方式 转载请注明出处:http://blog.csdn.NET/rosetta 64KB-4GB-64TB? 我记得大学的汇编课程.组成原理课里老师讲过实模式和保护模式的区别 ...

  5. 13 个免费的 PNG 图像的优化和压缩工具

    图像格式有许多种不同类型,在互联网上最常见的有JPEG.GIF.BMP.TIFF和PNG.每一种图像格式都有它自己的用途,比如GIF是用于动画的,JPEG是用于高清图片的,这种图片在保存或者调整大小后 ...

  6. SPSS数据分析—加权最小二乘法

    标准的线性回归模型的假设之一是因变量方差齐性,即因变量或残差的方差不随自身预测值或其他自变量的值变化而变化.但是有时候,这种情况会被违反,称为异方差性,比如因变量为储蓄额,自变量为家庭收入,显然高收入 ...

  7. Sprint2(12.6)

    Sprint1第二阶段 1.类名:软件工程-第二阶段 方案一:此方案操作界面只有前台.厨房 (1)前台:用户到前台点餐,服务员操作界面,勾选客人所在桌号(不可重复勾选),并输入所选菜品,可增.删.改所 ...

  8. org.springframework.jdbc.UncategorizedSQLException异常

    用到了mysql的TRUNCATE函数,这个关键字对spring事务有影响,最后换成了ROUND函数

  9. 使用robot frame selenium中遇到的问题汇总

    1.问题:robot运行时提示:[ WARN ] Keyword 'Capture Page Screenshot' could not be run on failure: No browser i ...

  10. 初始通过 FastClick.notNeeded 方法判断是否需要做后续相关处理

    其实前面几篇文章大家都遇到一些错误,很多时候呢,我并没有直接回复解决方案,不是LZ不想告诉大家,如果不想那就不写这个了,估计博客园啊CSDN啊那么多写博客的,很少有人把现用框架分享出来,既然分享就毫不 ...