add completed interpreter.js
This commit is contained in:
		
							parent
							
								
									f60da0d400
								
							
						
					
					
						commit
						cfb13f2812
					
				
					 1 changed files with 50 additions and 0 deletions
				
			
		
							
								
								
									
										50
									
								
								interpreter.js
									
										
									
									
									
										Normal file
									
								
							
							
						
						
									
										50
									
								
								interpreter.js
									
										
									
									
									
										Normal file
									
								
							|  | @ -0,0 +1,50 @@ | ||||||
|  | class Calculator { | ||||||
|  |     result; | ||||||
|  |     expression; | ||||||
|  | 
 | ||||||
|  |     /* | ||||||
|  |      Perform a calculation. | ||||||
|  | 
 | ||||||
|  |      @param {string} expr the expression to solve | ||||||
|  |      @return {Object} the result | ||||||
|  |      */ | ||||||
|  |     calculate(expr) { | ||||||
|  |         try { | ||||||
|  |             this.result = eval(expr); | ||||||
|  |         } catch(err) { | ||||||
|  |             alert(err); | ||||||
|  |         }; | ||||||
|  |     }; | ||||||
|  | 
 | ||||||
|  |     interactive() { | ||||||
|  |         while (true) { | ||||||
|  |             this.input = ``; | ||||||
|  | 
 | ||||||
|  |             this.input = (this.result != null) ? prompt(this.result) : prompt(); | ||||||
|  | 
 | ||||||
|  |             // Determine whether the user typed a value.
 | ||||||
|  |             if ((this.input) ? this.input.trim() : false) { | ||||||
|  |                 this.expression = this.input.trim(); | ||||||
|  |                 delete this.input; | ||||||
|  | 
 | ||||||
|  |                 // Solve the expression.
 | ||||||
|  |                 this.calculate(this.expression); | ||||||
|  |             } else { | ||||||
|  |                 break; | ||||||
|  |             } | ||||||
|  |         } | ||||||
|  |     } | ||||||
|  | 
 | ||||||
|  |     constructor() { | ||||||
|  |     }; | ||||||
|  | }; | ||||||
|  | 
 | ||||||
|  | 
 | ||||||
|  | function main() { | ||||||
|  |     let INSTANCE = new Calculator(); | ||||||
|  |     INSTANCE.interactive(); | ||||||
|  | }; | ||||||
|  | 
 | ||||||
|  | main(); | ||||||
|  | 
 | ||||||
|  | 
 | ||||||
		Loading…
	
	Add table
		Add a link
		
	
		Reference in a new issue