Friday, November 14, 2014

functional Javascript

A few good stuff online:

functional-javascript

Functional is a library for functional programming in JavaScript.

JavaScript Allongé

functional.js is a functional JavaScript library. It facilitates currying and point-free / tacit programming and this methodology has been adhered to from the ground up

The function existy is meant to define the existence of something. JavaScript has two values—null and undefined—that signify nonexistence. Thus, existy checks that its argument is neither of these things, and is implemented as follows

function existy(x) { return x != null }; 
Using the loose inequality operator (!=), it is possible to distinguish between null, undefined, and everything else. It’s used as follows
existy(null);
//=> false
existy(undefined);
//=> false
existy({}.notHere);
//=> false
existy((function(){})());
//=> false
existy(0);
//=> true
existy(false);
//=> true
The use of existy simplifies what it means for something to exist in JavaScript. Minimally, it collocates the existence check in an easy-to-use function. The second function mentioned, truthy, is defined as follows
function truthy(x) { return (x !== false) && existy(x) };
The truthy function is used to determine if something should be considered a synonym for true, and is used as shown here
truthy(false);
//=> false
truthy(undefined);
//=> false
truthy(0);
//=> true
truthy('');
//=> true
In JavaScript, it’s sometimes useful to perform some action only if a condition is true and return something like undefined or null otherwise. The general pattern is as follows:
{
if(condition)
return _.isFunction(doSomething) ? doSomething() : doSomething;
else
return undefined;
}
Using truthy, I can encapsulate this logic in the following way
function doWhen(cond, action) {
if(truthy(cond))
return action();
else
return undefined;
}
Now whenever that pattern rears its ugly head, you can do the following instead

function executeIfHasField(target, name) {
return doWhen(existy(target[name]), function() {
var result = _.result(target, name);
console.log(['The result is', result].join(' '));
return result;
});
}
The execution of executeIfHasField for success and error cases is as follows:
executeIfHasField([1,2,3], 'reverse');
// (console) The result is 3, 2, 1
//=> [3, 2, 1]
executeIfHasField({foo: 42}, 'foo');
// (console) The result is 42

No comments:

Post a Comment