Skip to content

Instantly share code, notes, and snippets.

@srdjan
Last active August 29, 2015 14:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save srdjan/978b0f52cb737dc646a0 to your computer and use it in GitHub Desktop.
Save srdjan/978b0f52cb737dc646a0 to your computer and use it in GitHub Desktop.
Simple functional refactoring
// 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));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment