TLDR;
Making all the same assumptions as below, this will work and of course is dead simple:
$scope.setOperand = function (operand) {
var prop = $scope['leftOperand'] === null ? 'leftOperand' : 'rightOperand';
$scope[prop] = +$scope[prop] + operand;
};
The key is this part: +$scope[prop]
That casts null
to 0, so you end up adding it to one side or the other, if it's null
or has a value (which is what the logic seems to do). Bergi pointed out that null
and null
for both values isn't handled, but I'd say the calculation should be done elsewhere:
$scope.calc = function(){
return eval(
+$scope.leftOperand // Cast if null to 0
+ ($scope.operator || '+') // Default to add if null
+$scope.rightOperand // Cast if null to 0
);
};
Assuming you have one left/right operand (and you're not trying to do multiple operations):
var $scope = {
operator: '-',
answer: null,
leftOperand: null,
rightOperand: 3,
};
We can start with:
$scope.setOperand = function (operand) {
var prop = ['leftOperand','rightOperand'].reduce(function(t, k) {
return $scope[k] === null ? k : t;
});
$scope[prop] = +$scope[prop] + operand;
};
https://jsfiddle.net/w89dLrqw/
Which is four lines. We can remove one line with a little hijinks:
$scope.setOperand = function (operand) {
[['leftOperand','rightOperand'].reduce(function(t, k) {
return $scope[k] === null ? k : t;
})].map(function(prop){$scope[prop] = +$scope[prop] + operand});
};
https://jsfiddle.net/b63x7aag/
Or, if you will:
$scope.setOperand = function (operand) {
[['leftOperand','rightOperand'].reduce(function(t, k) {return $scope[k] === null ? k : t;})]
.map(function(prop){$scope[prop] = +$scope[prop] + operand});
};
And another one (props to @bergi):
$scope.setOperand = function (operand) {
(function(prop){$scope[prop] = +$scope[prop] + operand})
(['leftOperand','rightOperand'].reduce(function(t, k){return !+$scope[k] ? k : t}));
};
https://jsfiddle.net/mh1bvhcj/1/
That last two look minified, and that last one runs "upside-down". I can't see how this is useful to write it this way just so it takes up very little horizontal space.
What I don't understand is what the else if ($scope.answer === null)
is in there for, since having answer === null
doesn't seem like it would affect the operands as far as I can tell. So this may or may not work, depending on what that's about.