• API
• FAQ
• Tools
• Archive
SHARE
TWEET

# Problem051

a guest Jan 14th, 2016 81 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
1. var test = '1+2';
2. var numbersArr = test.split(/[+,\-,*,\/]+/);
3. var signsArr = test.split(/[0-9]*/);
4. signsArr = signsArr.filter(function(e){return e});
5.
6. for(var i = 0; i < signsArr.length; i++){
7.
8.     //check the 1st number
9.     if(i === 0 && ((signsArr[i] === '*') || (signsArr[i] === '/'))){
10.
11.         if(signsArr[i] === '*'){
12.             numbersArr[i] = numbersArr[i] * numbersArr[i + 1];
13.         }
14.         if(signsArr[i] === '/') {
15.             numbersArr[i] = numbersArr[i] / numbersArr[i + 1];
16.         }
17.
18.         numbersArr.splice(i + 1, 1);
19.         signsArr.splice(i, 1);
20.     }
21.
22.     //check the mid numbers
23.
24.     if((i > 0 && i < signsArr.length - 1) && (signsArr[i] === '/')){
25.         numbersArr[i] = numbersArr[i] / numbersArr[i + 1];
26.         numbersArr.splice( i + 1, 1 );
27.         signsArr.splice(i, 1);
28.     }
29.
30.     if((i > 0 && i < signsArr.length - 1) && (signsArr[i] === '*')){
31.         numbersArr[i] = numbersArr[i] * numbersArr[i + 1];
32.         numbersArr.splice( i + 1, 1 );
33.         signsArr.splice(i, 1);
34.     }
35.
36.
37.     //check the last number
38.     if((i === signsArr.length - 1) && (signsArr[i] === '*' || signsArr[i] === '/')){
39.         if(signsArr[i] === '/'){
40.             numbersArr[numbersArr.length - 2] = numbersArr[numbersArr.length - 2] / numbersArr[numbersArr.length - 1];
41.         }
42.         if(signsArr[i] === '*'){
43.             numbersArr[numbersArr.length - 2] = numbersArr[numbersArr.length - 2] * numbersArr[numbersArr.length - 1];
44.         }
45.
46.         numbersArr.splice(numbersArr.length - 1, 1);
47.         signsArr.splice(signsArr.length - 1, 1);
48.     }
49.
50.
51. }
52.
53.
54. var number = Number(numbersArr[0]);
55.
56. for(var i = 0; i < signsArr.length; i++){
57.
58.     if(signsArr[i] === '-'){
59.         number -= Number(numbersArr[i + 1]);
60.     }
61.     if(signsArr[i] === '+'){
62.         number += Number(numbersArr[i + 1]);
63.     }
64.
65.
66. }
67.
68.
69. console.log(test);
70. console.log(signsArr);
71. console.log(numbersArr);
72. console.log(number);
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy.

Top