1
1
import { Summand } from './types' ;
2
2
const operators = new Set ( [ '+' , '-' , '*' , '/' ] ) ;
3
3
4
- // isValidCommand checks if the command is a allowed mathematical expression
5
- function isValidCommand ( s : string ) : boolean {
6
- s = s . replace ( / / g, '' ) ; // remove all spaces
7
- if ( s . length === 0 ) {
4
+ // isValidOperation checks if the operation is a allowed mathematical expression
5
+ function isValidOperation ( operation : string ) : boolean {
6
+ const cleanedOperation = operation . replace ( / / g, '' ) ; // remove all spaces
7
+ if ( cleanedOperation . length === 0 ) {
8
8
return false ;
9
9
}
10
- // allowed characters: 0-9, +, -, *, /, .
11
- const regex = / ^ [ \d + \- * / . ] + $ / ;
12
- if ( ! regex . test ( s ) ) {
10
+ if ( ! allowedChars ( cleanedOperation ) ) {
13
11
return false ;
14
12
}
15
- // operators cannot be adjacent to each other
16
- for ( let i = 0 ; i < s . length - 1 ; i ++ ) {
17
- if ( operators . has ( s [ i ] ) && operators . has ( s [ i + 1 ] ) ) {
18
- return false ;
19
- }
13
+ if ( ! noAdjacentOperators ( cleanedOperation ) ) {
14
+ return false ;
20
15
}
21
- // operators cannot be at the end of the string
22
- if ( operators . has ( s [ s . length - 1 ] ) ) {
16
+ if ( noOperatorsAtTheEnd ( cleanedOperation ) ) {
23
17
return false ;
24
18
}
25
19
return true ;
26
20
}
27
21
22
+ function allowedChars ( operation : string ) : boolean {
23
+ return / ^ [ \d + \- * / . ] + $ / . test ( operation ) ;
24
+ }
25
+
26
+ function noAdjacentOperators ( operation : string ) : boolean {
27
+ for ( let i = 0 ; i < operation . length - 1 ; i ++ ) {
28
+ if ( operators . has ( operation [ i ] ) && operators . has ( operation [ i + 1 ] ) ) {
29
+ return false ;
30
+ }
31
+ }
32
+ return true ;
33
+ }
34
+
35
+ function noOperatorsAtTheEnd ( operation : string ) : boolean {
36
+ return operators . has ( operation [ operation . length - 1 ] ) ;
37
+ }
38
+
28
39
// evaluate evaluate a mathematical expression
29
40
function evaluate ( s : string ) : string {
30
- if ( ! isValidCommand ( s ) ) {
41
+ if ( ! isValidOperation ( s ) ) {
31
42
throw new Error ( 'Invalid command' ) ;
32
43
}
33
44
s = s . replace ( / / g, '' ) ; // remove all spaces
@@ -72,4 +83,4 @@ const parseExpression = (s: string): Summand[] => {
72
83
return summands ;
73
84
}
74
85
75
- export { isValidCommand , evaluate } ;
86
+ export { evaluate } ;
0 commit comments