Functional JS Flashcards
functions in objects v. global
var a = { a: 24, fun: function() { return this}}
a.fun();
//{ a: 24, fun: function() { return this}}
// points to the object ‘a’, itself.
afunc = a.fun
afunc()
// some object, probably window.
Four starting rules
- Avoid assigning variables more than once.
- Do not use eval
- Do not modify core objects like array and function
- Favor functions over methods
Existy and Truthy and why use them
function existy(x) { return x != null };
distinguishes between null, undefined, and everything else. null and undefined return False, everything else, True.
function truthy(x) { return ( x !== false ) && existy(x) };
should something be considered a synonym for true?
truthy(undefined);
false
truthy(0);
true
truthy(‘ ‘);
true
this kind of logic is often needed:
{ if(condition) _.isFunction(doSomething) ? doSomething() : doSomething; else return undefined };
so…
function doWhen(cond, action) {
if truthy(cond)
return action();
else
return undefined;
}
Functional Programming
in a nutshell
- Identifying an abstraction and building a function for it
- Using existing functions to build more complex abstractions
- Passing existing functions to other functions to build even more complex abstractions
Basic Metaprogramming with this
function Point2D(x,y) { this._x=x; this._y = y;}
new Point2D(1,2);
//makes a point
function Point3D(x,y,z) { Point2D.call(this, x,y); this._z = z; }
new Point3D(1,2,3);
Applicative Programming
Calling by function B of function A which then calls function B again.
This is seen in map, reduce and filter - but many other functional constructs seen in underscore.js
Collection-Centric Programming
seen in Python style unpacking
_.map({a:1, b:2}, _.identity)
// [1 , 2]
//accepts k and v
_.map({a:1, b:2}, function(k,v){ return [k , v]};
//[[a,1], [b,2]]
//third argument is the collection itself
_.map({a:1, b:2}, function(k,v, col)
{ return [k , v, _.keys(col)]};
// [[a,1,[a,b]], [b,2,[a,b]]]
“It’s better to have 100 functions operate on one data structure than 10 functions on 10 data structures”
-Alan Perlis
sortBy, groupBy, countBy
collection-centric programming #2
- _.sortBy - accepts collection and sorting function returns objects in collection sorted by function. _.sortBy(albums, function(a) return a.year)
- _.groupBy - accepts collection and function, returns object whose keys are the values returned by function and whose values are the objects in the collection that satisfy the grouping.
- _.countBy - accepts collection and function. Object whose keys are values returned by function and values are counts seen in original collection.
4 Definitions of Scope
- The value of the this binding
- The execution context defined by the value of the this binding
- The lifetime of a variable
- The variable value resolution scheme, or the lexical bindings
Lexical Scoping
Grouping of names with values according to the surrounding source code.
- starts at innermost level, looks for name, continues outward until it finds it.
Dynamic scoping does this by assigning a stack to a key in a global namespace. The stack holds everything the corresponding key refers to, in the order in which it was declared. Fetching it the value gets the most recent value. So any arbitrary function can change the global value of a key - can’t know what that key will return until we know what the caller did.
Functional Scope
function strangeIdentity(n) {
for(var i = 0; i < n; i++);
return i; };
strangeIdentity(139);
//139
So ‘i’ is found inside function.
function f() {
this[‘a’] = 200;
return this[‘a’] + this[‘b’];
}
var globals = {‘b’ : 2}
f(_.clone(globals));
// 202
Closures
p. 59
Hand in hand with functions as first-class objects.
Function that captures values near where it was born.
Closure is a function that captures the external bindings (NOT it’s own arguments) contained in the scope in which it was defined to be used later (even after the scope has completed).
function whatWasTheLocal() {
var CAPTURED = ‘oh hai’;
return function() {
return “The local was: “ + CAPTURED;
};
}
// notice that ‘FUN’ is stored and used later
function averageDamp(FUN){
return function(n){
return average([n, FUN(n)])};
}
Free variables
p. 62
Free variables are related to closures in that it is these free variables that will be closed over by the closure.
Basic idea of closure is that if a function contains inner functions, then those functions can see the variables therein.
These variables can be captured and carried along for later use by inner functions via return.
Higher order function
- It is first-class
- accepts a function as an argument
- returns a function