Declarative style JavaScripting and the curious case of underscore.js.
- Presented at BangaloreJS Eleventh meetup: http://bangalorejs.org/eleventh.html
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
Functional programming in JavaScript and the curious case of _.js
1. {
Functional programming in JavaScript
… and the curious case of _.js
Om Shankar
JavaScripter @ InMobi
bit.ly/omshankar
2. Functional programming is the use of functions that
transform values into units of abstraction, subsequently
used to build software systems.
3. Do Something !
– by doing this, and then that,
– and don’t forget to do this at the end of all that.
Get Something Done !
– I don’t care how you do it,
– also, when I want it done again, it should be as easy as it was the first
time.
Declarative programming: stackoverflow.com/a/8357604/1249219
5. • Should travel in First Class
• Should be Pure, hence, should be re-usable
• Should be Applicative
- function A supplied to B should perform actions in B’s context.
6. Strings are first class in JS,
- so are functions with all possible operations
// Both can be stored
var string = "BangaloreJS";
var stringFn = function() { return "BangaloreJS"; }
// can be used on the fly, as an expression:
// string
"BangaloreJS";
"BangaloreJS".slice(3);
// function
"BangaloreJS" + (function(){ return " Rocks !!"; }());
7. A pure function
•
•
•
•
takes argument(s)
returns value(s)
returns same value(s) for same argument(s)
does nothing else !
Arguments
Return value
8. An impure function
• takes argument(s)
• returns value(s)
• reads/writes external states, for
eg., modifies global DOM, objects, arrays.
Read State
Arguments
Return value
tightly coupled with read state
Change State
9. _. map
reduce / reduceRight
find / detect / where
filter / reject
every / some
...
11. Functions taking functions as parameters
function repeat(times, fn) {
return _.map(_.range(times), fn);
}
12. Functions returning functions as value
var numData = [1,2,null,4,5];
_.reduce(numData, function(tot, curr) {
return tot * curr;
});
// Problem?
// Solution: function returning modified safe function
// and not imperatively modified data
// though what we actually do is modify data on the fly
13. RxJS
- Reactive extensions for JS by Microsoft
{
Declarative JavaScript Libraries
Bilby.js - bilby.brianmckenna.org
Allong.es - github.com/fogus/lemonad