-
-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathVariablesCollection.cs
More file actions
79 lines (64 loc) · 2.6 KB
/
Copy pathVariablesCollection.cs
File metadata and controls
79 lines (64 loc) · 2.6 KB
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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
using System;
using System.Collections;
using System.Collections.Generic;
namespace StringMath
{
/// <summary>A collection of variables.</summary>
internal interface IVariablesCollection : IEnumerable<string>
{
/// <summary>Overwrites the value of a variable.</summary>
/// <param name="name">The variable's name.</param>
/// <param name="value">The new value.</param>
void SetValue(string name, double value);
/// <summary>Gets the value of the variable.</summary>
/// <param name="name">The variable's name.</param>
/// <param name="value">The value of the variable.</param>
/// <returns><c>true</c> if the variable exists, false otherwise.</returns>
bool TryGetValue(string name, out double value);
/// <summary>Tells whether the variable is defined or not.</summary>
/// <param name="name">The name of the variable.</param>
/// <returns>True if variable was previously defined. False otherwise.</returns>
bool Contains(string name);
/// <inheritdoc cref="SetValue(string, double)" />
double this[string name] { set; }
}
/// <inheritdoc />
internal class VariablesCollection : IVariablesCollection
{
public static readonly VariablesCollection Default = new VariablesCollection();
private readonly Dictionary<string, double> _values = new Dictionary<string, double>();
static VariablesCollection()
{
Default["PI"] = Math.PI;
Default["E"] = Math.E;
}
/// <inheritdoc />
public void CopyTo(IVariablesCollection other)
{
other.EnsureNotNull(nameof(other));
foreach (var kvp in _values)
{
other.SetValue(kvp.Key, kvp.Value);
}
}
/// <inheritdoc />
public IEnumerator GetEnumerator() => _values.GetEnumerator();
/// <inheritdoc />
public double this[string name]
{
set => SetValue(name, value);
}
/// <inheritdoc />
public void SetValue(string name, double value)
{
name.EnsureNotNull(nameof(name));
_values[name] = value;
}
/// <inheritdoc />
public bool TryGetValue(string name, out double value)
=> _values.TryGetValue(name, out value) || Default._values.TryGetValue(name, out value);
IEnumerator<string> IEnumerable<string>.GetEnumerator() => _values.Keys.GetEnumerator();
/// <inheritdoc />
public bool Contains(string name) => _values.ContainsKey(name);
}
}