Книга: Functional Programming in JavaScript
Назад: The application – an e-commerce website
Дальше: Functional programming

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');

Tip

Downloading the example code

You can download example code files for all Packt books you have purchased from your account at . If you purchased this book elsewhere, you can visit and register to have the files e-mailed directly to you.

As you can see, this code is very basic. What if there were many more coffee styles than just the three we have here? What if there were 20? 50? What if, in addition to size, there were organic and non-organic options. That could increase the lines of code extremely quickly!

Using this method, we are telling the machine what to print for each coffee type and for each size. This is fundamentally what is wrong with imperative code.

Назад: The application – an e-commerce website
Дальше: Functional programming

bsn
thank
Vesa Karvonen
I hope you don't mind, but I’d like to point you and your readers to my high-performance optics library for JavaScript that is in production use in multiple projects, has comprehensive support for partial optics and interactive documentation: https://calmm-js.github.io/partial.lenses/ (this takes a moment to load — be patient!)