0

I'm taking random values from array A and B and trying to compare their solved values, is not working because values in arrays are strings, how to get them to number and solve them?

.controller('questions', function($scope) { var A = ['6-2', '7+3', '8*1', '9/3', '8+1']; var B = ['1+5', '7-3', '10-5', '10/2', '3*2']; var questionA = A[Math.floor(Math.random() * A.length)]; var questionB = B[Math.floor(Math.random() * B.length)]; if (questionA > questionB) { console.log('It\'s bigger '); } else { console.log('It\'s smaller'); } }); 
1
  • What do you mean? You want '7+3' to magically be 10? Commented Jun 8, 2016 at 7:42

2 Answers 2

3

You can use $scope.$eval() to get the result of the equation:

var answerA = $scope.$eval(questionA), answerB = $scope.$eval(questionB); if(answerA > answerB) 
Sign up to request clarification or add additional context in comments.

4 Comments

@Rajesh Did you read my answer ? It's using $scope.$eval not js eval
@MartijnWelker my apologies.
Found a good answer eval vs $eval. Also @MartijnWelker You can also include $parse. Have not used it but can be good variety for answer.
@Rajesh $eval calls $parse internally
0

An alternate to eval

JSFiddle

var A = ['6-2', '7+3', '8*1', '9/3', '8+1']; var B = ['1+5', '7-3', '10-5', '10/2', '3*2']; var len = Math.max(A.length, B.length); for (var i = 0; i < len; i++) { var r1 = evaluate(A[i]); var r2 = evaluate(B[i]); var msg = "It's " + (+r1 > +r2 ? "Bigger" : "Smaller"); console.log(msg, r1, r2); } function evaluate(str) { var opReg = /[-+\/\*]/g; var op_arr = str.match(opReg); var result = 0; var sortOrder = { "*": 1, "/": 2, "+": 3, "-": 4 } op_arr.sort(function(a, b) { var s1 = sortOrder[a]; var s2 = sortOrder[b]; return s1 > s2 ? 1 : s1 < s2 ? -1 : 0; }).forEach(function(op) { var val_arr = getValueArr(str, op) result = calculate(val_arr, op); str = str.replace(val_arr[0] + op + val_arr[1], result) }); return result; } function getValueArr(str, op) { var r = str.split(op); var v1 = 0; var v2 = 0; var opReg = /[-+\/\*]/g; v1 = opReg.test(r[0]) ? r[0].split(opReg).reverse()[0] : r[0]; v2 = opReg.test(r[1]) ? r[1].split(opReg)[0] : r[1]; return [v1, v2]; } function calculate(val, op) { switch (op) { case "-": return +val[0] - +val[1]; case "+": return +val[0] + +val[1]; case "*": return +val[0] * +val[1]; case "/": return +val[0] / +val[1]; } return 0; } evaluate('6-2+4*2')

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.