@@ -3,13 +3,55 @@ import { Stack } from '../utils/stack';
33import { OperatorTokens } from './tokens' ;
44
55export class Postfix {
6+ /**
7+ * Input infix string
8+ *
9+ * @private
10+ * @type {string }
11+ */
612 private text : string ;
13+
14+ /**
15+ * Position of the current token
16+ *
17+ * @private
18+ * @type {number }
19+ */
720 private pos : number = 0 ;
21+
22+ /**
23+ * Final output queue
24+ *
25+ * @private
26+ * @type {Queue<string> }
27+ */
828 private outputQueue : Queue < string > ;
29+
30+ /**
31+ * Data structure to store the operators
32+ *
33+ * @private
34+ * @type {Stack<string> }
35+ */
936 private operatorStack : Stack < string > ;
1037 private textLength : number ;
11- private operatorCount = 0 ;
12- private numberCount = 0 ;
38+
39+ /**
40+ * Number of operators encountered till `this.pos`
41+ *
42+ * @private
43+ * @type {number }
44+ */
45+ private operatorCount : number = 0 ;
46+
47+ /**
48+ * Number of operands encountered till `this.pos`
49+ * @date 9/1/2023 - 1:44:00 PM
50+ *
51+ * @private
52+ * @type {number }
53+ */
54+ private numberCount : number = 0 ;
1355
1456 constructor ( text : string ) {
1557 this . text = text ;
@@ -81,6 +123,7 @@ export class Postfix {
81123 private parseRightParenthesis ( ) {
82124 this . consumeToken ( ) ;
83125
126+ // Pop all operators from the stack until we encounter a left parenthesis.
84127 while ( this . operatorStack . peek ( ) !== '(' ) {
85128 if ( this . operatorStack . size ( ) === 0 ) {
86129 throw new Error ( 'Mismatched Parenthesis' ) ;
@@ -101,13 +144,15 @@ export class Postfix {
101144 this . consumeToken ( ) ;
102145 const token1 = OperatorTokens . get ( o1 ) ! ;
103146
147+ // While there is an operator token, o2, at the top of the stack
104148 while ( this . operatorStack . size ( ) > 0 ) {
105149 const o2 = this . operatorStack . peek ( ) ! ;
106150
107151 if ( o2 === '(' ) {
108152 break ;
109153 }
110154
155+ // If o1 is left-associative and its precedence is less than or equal to that of o2,
111156 const token2 = OperatorTokens . get ( o2 ) ! ;
112157 if (
113158 token2 . precedence > token1 . precedence ||
@@ -126,6 +171,7 @@ export class Postfix {
126171 private parseNumber ( ) : string {
127172 this . numberCount ++ ;
128173 let str = '' ;
174+
129175 while ( this . pos < this . textLength ) {
130176 const token = this . getCurrentToken ( ) ;
131177 if ( token === ' ' || token === ')' ) {
@@ -134,6 +180,7 @@ export class Postfix {
134180 str += token ;
135181 this . consumeToken ( ) ;
136182 }
183+
137184 return str ;
138185 }
139186
0 commit comments