-
Notifications
You must be signed in to change notification settings - Fork 0
/
Calculator.cs
56 lines (47 loc) · 1.35 KB
/
Calculator.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Globalization;
using System.Linq;
namespace FunWithMEF
{
[Export(typeof(ICalculator))]
class Calculator : ICalculator
{
[ImportMany]
IEnumerable<Lazy<IOperation, IOperationData>> operations;
public string Calculate(string input)
{
int left;
int right;
var fn = FindFirstNonDigit(input);
if (fn < 0)
{
return "Could not parse command.";
}
try
{
left = int.Parse(input.Substring(0, fn));
right = int.Parse(input.Substring(fn + 1));
}
catch (Exception)
{
return "Could not parse command.";
}
var operation = input[fn];
foreach (var i in operations.Where(i => i.Metadata.Symbol.Equals(operation)))
{
return i.Value.Operate(left, right).ToString(CultureInfo.InvariantCulture);
}
return "Operation Not Found!";
}
private int FindFirstNonDigit(String s)
{
for (int i = 0; i < s.Length; i++)
{
if (!(Char.IsDigit(s[i]))) return i;
}
return -1;
}
}
}