Simple example of functional refactoring

I received a couple of request to show more examples of using functional techniques after my ‘Functional JavaScript’ workshop at Cowerks.

So, I’ll be putting out some examples – simple and to the point… Hopefully 😉

// original code
function printTrace(log) {
for (var i = 0; i < log.length; i++) {
var entry = log[i];
var args = entry.args;
var argstring = "(";
for (var j = 0; j < args.length - 1; j++) {
argstring += args[j].toString() + ",";
}
if (args.length > 0) {
argstring += args[args.length - 1].toString();
}
argstring += ")";
console.log(log.id + ": " + entry.op + argstring + ' returned: ' + entry.result);
}
}
// ...after replacing explicit loops with 'map'
function printTrace(log) {
log.map(function(entry) {
console.log(log.id + ": " + entry.op + '(' + entry.args + ')' + ' returned: ' + entry.result);
});
}
// ...finally, using shorthand for anonymous functions -'fat arrow' from ES6
function printTrace(log) {
log.map(entry => console.log(log.id + ": " + entry.op + '(' + entry.args + ')' + ' returned: ' + entry.result));
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: