Don't wanna be here? Send us removal request.
Text
What is Currying in JavaScript?
Currying in JavaScript is the practice of what is known as partial function application - the ability to preset one argument for a function for other arguments to be applied versus the first at a later time. This practice was invented Gottlob Frege, but was later perfected by Haskell Curry, for whom the practice is named after.
A simple example
Adder functions in JavaScript are pretty common basic examples, so we'll start with transforming a basic adder function into a curried adder function. Take your basic JavaScript adder:
function add(a, b) { return a + b; }
Simple enough right? The function receives two arguments and returns the sum of those two arguments. What if we wanted to developer an adder where we could preset one of those arguments? The answer is simple - we introduce a curried function to be returned!
function curriedAdd(a) { return function (b) { return a + b; } }
Now with this newly minted curried function, we get a bit more functionality than we had previously with our regular adder, For example, say that we want to create a preset adder that adds 5 to the provided argument:
var addFive = curriedAdd(5); // addFive becomes a function with a preset 'a' argument of 5! var seven = addFive(2); // seven now equals 7!
We can even skip the preset application and use our curried function as a regular adder:
var seven = curriedAdd(5)(2); // seven now equals 7 because we are immediately resolving the first function returned by curriedAdd(5) with the (2)!
How this becomes useful
This becomes extremely useful when we find that there are function patterns that we use often that only have small differences between them. A common use case is the case of reducer functions. Many times, you want to reduce an array of objects that calculate the sum of a particular field on those objects. We might calculate that sum like this:
// Let's assume we have an array of items that a user has purchased, but we want to calculate the sum of the cost var SalesList = [ {item: 'Baseball glove', cost: 24.95, tax: .69, description: 'Catches baseballs'}, {item: 'Baseball', cost: 4.99, tax: .19, description: 'For catching!'}, {item: 'Glove oil', cost: 9.99, tax: .27, description: 'For keeping your glove loose!'} ]; // We could calculate this sum by using Array.prototype.reduce: var total_cost = SalesList.reduce(function (previousValue, currentItem) { return previousValue + currentItem['cost']; });
But what if we want to calculate the total tax of all of the items in our SalesList array? Our reducer pattern is basically the same - we would be rewriting the same code over again. This pattern will remain pretty much the same from application to application, however the field that is chosen to reduce will be what changes. How can we avoid having to rewrite code in this scenario? Simple, write a curried reducer function that accepts a single preset argument - the field of which we would like to reduce the sum of.
// Write a curried function that returns a new reducer function with our 'field' argument preset: function reduceSumByField(field) { return function (previousValue, currentValue) { return previousValue + currentValue[field]; } }
Now to calculate different totals on an array of objects, we never have to rewrite that reducer function again - just pass in the curried function with the selected field as the argument.
// Get our total cost: var total_cost = SalesList.reduce(reduceSumByField('cost')); // Get our total tax: var total_tax = SalesList.reduce(reduceSumByField('tax'));
Wrapping Up
In functional languages like JavaScript, we get a lot of freedom for function composition to avoid having to rewrite code over and over again. By using currying, you can gain more control over your function composition, save time, and get more done.
0 notes
Text
An Introduction to OOP in ES5
A lot of programmers enter the world of functional programming via JavaScript and remark on how utterly easy it is to become immersed in. A lot of things just “work”. The loose type and syntax make for relatively seamless coding. Some people would argue that this is a serious detriment to the language ecosystem as a whole with the lack of enforced type and structure, so over the years new features have been added to the JS ecosystem to encourage stricter standards and interoperability. Today I will be demonstrating the basics of objected oriented JavaScript, via ES5 and the prototype property in comparison to a Class in PHP - an extremely common server language that most of you should be familiar with.
Our PHP Class
So we'll begin with a mock class in PHP to demonstrate how we would apply similar features from a PHP class to an object in JavaScript.
class User { public $id; public $username; public $hometown; public function __construct($id, $username, $hometown) { $this->id = $id; $this->username = $username; $this->hometown = $hometown; } public function changeUsername($new_name) { $this->username = $new_name; return $this; } public function changeHometown($new_town) { $this->hometown = $new_town; return $this; } }
The Constructor
The first piece of functionality for transcribing this class from PHP to JavaScript we'll worry about will be the actual constructor function, which accepts three arguments to set the three basic props on our newly minted JavaScript object. In JS, constructors are pure functions that are instantiated into objects using the `new` keyword. Our JS constructor would look something like this:
function User(id, username, hometown) { this.id = id; this.username = username; this.hometown = hometown; } // Now let's try instantiating our newly created constructor var user = new User(1, 'Westopher', 'Seattle'); // the `user` variable would now look something like an object literal like this: user === { id = 1, username = 'Westopher', hometown = 'Seattle' }
In other languages, objects are referred to by 'class'. In JavaScript, being a functional language, we refer to objects by 'Types'. We just designated our new 'User'.
Defining Methods
Now that we've designated a new Type, created a constructor, and assigned some properties, now it's time to assign some methods to our new type!
Following the previous pattern for how we defined our new Type and our constructor, you might be tempted to try to define our new Type's methods inside of the constructor, like so:
function User(id, username, hometown) { this.id = id; this.username = username; this.hometown = hometown; this.changeUsername = function(new_name) { this.username = new_name; return this; } this.changeHometown = function(new_town) { this.hometown = new_town; return this; } }
Initially, this might seem like a neat, effective way of structuring our class. It is well encapsulated and easily readible by other developers, however, there is a major issue that we face when we define a new Type in this manner. In traditional class based programming, a multitude of objects of the same type can be instantiated and when a method is called on one of those objects, the method is sourced from the original class. However, JavaScript is not built like that. If we were to build 1000 of these user objects, we would see instantiated 1000 instances of each of these methods in memory, which would create a fairly large memory load. So what is our answer for this issue? The prototype object.
The Prototype
All Types in JavaScript have a prototype object attached to them. When instantiating multiple copies of the same Type, this is where we source our methods from. To define a new method, we attach the method to the prototype property of the constructor:
// Our changeUsername() method: User.prototype.changeUsername = function (new_name) { this.username = new_name; return this; } // Our changeHometown() method: User.prototype.changeHometown = function (new_town) { this.hometown = new_town; return this; }
Now if we were to create a list of multiple users, we're not hogging memory by creating redunant copies of our User methods on each user. Instead, when a User object needs to call a method, it simply accesses it's own prototype object and sources the method from there with the context of the current object.
Putting it All Together
To wrap things up, this is what our final User object would look like in JavaScript transcribed from our PHP class above:
// Constructor and Type definition function User(id, username, hometown) { this.id = id; this.usernamae = username; this.hometown = hometown; } // Now we define our methods for our User Type User.prototype.changeUsername = function (new_name) { this.username = new_name; return this; } User.prototype.changeHometown = function (new_town) { this.hometown = new_town; return this; }
Thanks for checking out our Intro to Object Oriented JavaScript in ES5! Stay tuned for our next blog in the series: Intermediate Object Oriented JavaScript, introducing extensability.
0 notes
Text
Moving Forward
We are not just your average, run-of-the-mill software development company. Boone strives to provide you with whatever your organization needs that is equally reliable, successful, and easy on your wallet.

0 notes