public TokensTape ExecuteMostPriorityOperation(TokensTape tokensTape) { var @operator = FindMostPriorityOperator(tokensTape); if (@operator.Previous == null || @operator.Next == null) { throw new Exception("Wrong tokens input!"); } var left = (Number)@operator.Previous.Value; var right = (Number)@operator.Next.Value; var mathOperation = (IMathOperation)@operator.Value; var result = mathOperation.ExecuteBinary(left, right); var replacement = new[] { @operator.Previous, @operator.Next, @operator }; var newTokens = Replace(replacement, result, tokensTape); var newTape = new TokensTape(newTokens); return(newTape); }
private LinkedListNode <IToken> FindMostPriorityOperator(TokensTape tokensTape) { var operators = tokensTape.Enumerate() .Where(x => x.Value is IMathOperation) .ToArray(); var maxPriority = operators.Max(x => x.Value.Priority); return(operators .First(o => o.Value.Priority == maxPriority)); }
private IEnumerable <IToken> Replace(LinkedListNode <IToken>[] replacement, IToken result, TokensTape tokensTape) { foreach (var token in tokensTape.Enumerate()) { if (token == replacement.First()) { yield return(result); } if (replacement.Any(r => r == token)) { continue; } yield return(token.Value); } }