Skip to content

Commit 0cb6cd2

Browse files
authored
Create Fruit string calculator.js
1 parent cb0db81 commit 0cb6cd2

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed

Fruit string calculator.js

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
/*
2+
Description:
3+
Given a string of words and numbers. Extract the expression including:
4+
5+
the operator: either addition or subtraction
6+
the two numbers that we are operating on
7+
Return the result of the calculation.
8+
9+
Example:
10+
11+
"Panda has 48 apples and loses 4" returns 44
12+
13+
"Jerry has 34 apples and gains 6" returns 40
14+
15+
"loses" and "gains" are the only two words describing operators.
16+
17+
Should be a nice little kata for you :)
18+
19+
Note: No fruit debts nor bitten apples = The numbers are integers and no negatives
20+
*/
21+
22+
function calculate(string) {
23+
const arr=string.replace(/[^0-9\s]/g,'').trim().replace(/\s+/g,' ').split(' ')
24+
if (string.match(/loses/g)){
25+
return arr[0]*1-arr[1]*1
26+
}
27+
return arr[0]*1+arr[1]*1
28+
}

0 commit comments

Comments
 (0)