So I am trying to improve my approach to parsing. So I was adding this to a property called ledHelp:
'+':function(left, right){ this.value = left.value + right.value; this.instructions = 'Take '+left.value+' and ADD to '+right.value+' to get '+this.value; out('+:', this.instructions); }, '*':function(left, right){ this.value = left.value * right.value; this.instructions = 'Take '+left.value+' and MULTIPLY by '+right.value+' to get '+this.value; out('*:', this.instructions); }, '/':function(left, right){ this.value = left.value / right.value; this.instructions = 'Take '+left.value+' and DIVIDE by '+right.value+' to get '+this.value; out('/:', this.instructions); }, '-':function(left, right){ this.value = left.value - right.value; this.instructions = 'Take '+left.value+' and SUBTRACT to '+right.value+' to get '+this.value; out('-:', this.instructions);}, '**':function(left, right){ this.value = Math.pow(left.value, right.value); this.instructions = 'Take '+left.value+' and RAISE IT to the POWER '+right.value+' to get '+this.value; out('**:', this.instructions); }, '^':function(left, right){ this.value = Math.pow(left.value, right.value); this.instructions = 'Take '+left.value+' and RAISE IT to the POWER '+right.value+' to get '+this.value; out('^:', this.instructions) }
And I see the incredible similarity (it was copied and pasted) and that irritated me. As it should all good programmers. But I was having a hard time coming up with how to manage this. And then it hit me: iterate over an array with the different stuff and plug-n-play. Notice in the code below how I use functions as data and also rely upon closures:
var ops = [ ['+', function(l,r) {return l+r}, 'ADD to '], ['-', function(l,r) {return l-r}, 'SUBTRACT '], ['*', function(l,r) {return l*r}, 'MULTIPLY by '], ['/', function(l,r) {return l/r}, 'DIVIDE by '], ['^', function(l,r) {return Math.pow(l,r)}, 'RAISE it to the POWER '], ['**', function(l,r) {return Math.pow(l,r);}, 'ADD to '], ]; $.each(ops, function(index, op) { var id = op[0]; var operator = op[1]; var description = op[2]; instructions.ledHelp[id] = function(left, right) { //overwrites above if needed this.value = operator(left.value, right.value); this.instructions = 'Take '+left.value+' and '+description+right.value+' to get '+this.value; out(id+':', this.instructions); }; });
Which would you prefer to maintain? And notice that if I want to comment out the instructions bit, I do it once, not once for each operation. And to add more, I write some more code in the template and add an extra bit on the array. I could even assemble the array from various bits if I wanted to.
Post a Comment