lib/map: document `Map.has_key` and implement it efficienlty
authorJean Privat <jean@pryen.org>
Fri, 6 Mar 2015 04:07:21 +0000 (11:07 +0700)
committerJean Privat <jean@pryen.org>
Fri, 6 Mar 2015 04:20:55 +0000 (11:20 +0700)
Signed-off-by: Jean Privat <jean@pryen.org>

lib/standard/collection/abstract_collection.nit
lib/standard/collection/hash_collection.nit

index 20d1584..d38e001 100644 (file)
@@ -416,7 +416,14 @@ interface MapRead[K, V]
                return default
        end
 
-       # Alias for `keys.has`
+       # Is there an item associated with `key`?
+       #
+       #     var x = new HashMap[String, Int]
+       #     x["four"] = 4
+       #     assert x.has_key("four") == true
+       #     assert x.has_key("five") == false
+       #
+       # By default it is a synonymous to `keys.has` but could be redefined with a direct implementation.
        fun has_key(key: K): Bool do return self.keys.has(key)
 
        # Get a new iterator on the map.
@@ -987,6 +994,8 @@ interface CoupleMap[K, V]
                        return c.second
                end
        end
+
+       redef fun has_key(key) do return couple_at(key) != null
 end
 
 # Iterator on CoupleMap
index b62d876..cdc7906 100644 (file)
@@ -274,6 +274,7 @@ class HashMap[K, V]
 
        redef var keys: RemovableCollection[K] = new HashMapKeys[K, V](self)
        redef var values: RemovableCollection[V] = new HashMapValues[K, V](self)
+       redef fun has_key(k) do return node_at(k) != null
 end
 
 # View of the keys of a HashMap