|
Revision 2318, 1.1 KB
(checked in by Chuck.Esterbrook, 2 years ago)
|
|
Added IDictionary<of TKey, TValue>.get(key as TKey, default as TValue) as TValue
|
-
Property svn:eol-style set to
native
|
| Line | |
|---|
| 1 | namespace Cobra.Lang |
|---|
| 2 | |
|---|
| 3 | extend IDictionary<of TKey, TValue> |
|---|
| 4 | |
|---|
| 5 | def clone as IDictionary<of TKey, TValue> # CC: as same |
|---|
| 6 | """ |
|---|
| 7 | Returns a new dictionary with the contents of this dictionary. |
|---|
| 8 | Does not clone the contents themselves. |
|---|
| 9 | This is sometimes known as a "shallow copy". |
|---|
| 10 | """ |
|---|
| 11 | ensure |
|---|
| 12 | result is not this |
|---|
| 13 | result.count == .count |
|---|
| 14 | result.typeOf is .typeOf |
|---|
| 15 | body |
|---|
| 16 | type = .typeOf |
|---|
| 17 | newDict = type(this) |
|---|
| 18 | return newDict |
|---|
| 19 | |
|---|
| 20 | def get(key as TKey, default as TValue) as TValue |
|---|
| 21 | """ |
|---|
| 22 | Returns the value for the given key, or returns the default if the key is not found. |
|---|
| 23 | """ |
|---|
| 24 | ensure not .containsKey(key) implies result == default |
|---|
| 25 | value as TValue |
|---|
| 26 | if .tryGetValue(key, out value), return value |
|---|
| 27 | else, return default |
|---|
| 28 | |
|---|
| 29 | |
|---|
| 30 | class TestIDictionaryExtensions |
|---|
| 31 | |
|---|
| 32 | test |
|---|
| 33 | a = Dictionary<of String, int>() |
|---|
| 34 | |
|---|
| 35 | b = a.clone |
|---|
| 36 | assert b is not a |
|---|
| 37 | assert b.count == 0 |
|---|
| 38 | |
|---|
| 39 | a = {'x': 1, 'y': 2} |
|---|
| 40 | b = a.clone |
|---|
| 41 | assert b is not a |
|---|
| 42 | assert b.count == 2 |
|---|
| 43 | assert b['x'] == 1 and b['y'] == 2 |
|---|
| 44 | |
|---|
| 45 | d = {'a': 1, 'b': 2} |
|---|
| 46 | assert d.get('a', 0) == 1 |
|---|
| 47 | assert d.get('c', 1) == 1 |
|---|