What is ts-map?
it is a Map structure like ES6 Map. Map is similar to the object, but also a set of key-value pairs, but the "key" range is not limited to strings, various types of values (including objects) can be used as a key.
Installation
npm install ts-map
Usage
use in typescript file
map.set1, "hello"map.setk2, "ts".setk3, "map" map.get1 // "hello"map.getk2 // "world"map.size // 3map.keys // [1, [2], true]map.values // ["hello", "ts", "map"] map.forEach// 1 ':' 'hello'// [ 2 ] ':' 'ts'// true ':' 'map'
Getting started
Constructor with parameter
You can pass in the default parameters in the constructor:
console.logmap.get1 // ok
Class generic
support define generic for ts-map
map.set2, // work map.set3, "jack" // sorry, error
If you do not define generics, but in the constructor passed in the parameters, you also need follow the generic rules.If you do not use generics, you can set any type of key-value pairs for the map.
API
size: number
return the Map's size
map.set2, map.size // 2
set(k: K, v: V): TsMapInter<K, V>
set a key-value to Map, support chain called.
map.settrue, "1"map.set1, "hello".set2, "world"
Notice: Only the reference to the same object, Map structure will be regarded as the same key.
map.setk, "hello"map.getk // hellomap.get // undefind
If the same key is assigned multiple times, the following value will overwrite the previous value.
map.set1, "111".set1, "222"map.get1 // 222
get(k: K): V | undefined
Return the value of the corresponding key,if dosn't include, return undefind.
map.set1, "111"map.get1 // 111map.get2 // undefind
has(k: K): boolean
Determine if a key is included.
map.set1, "111"map.has1 // truemap.has2 // false
delete(k: k): boolean
Delete all the corresponding keys and its value, if detele success, return true. else return false.
map.set1, "111"map.set2, "222"map.delete1map.has1 //falsemao.size // 1
clear(): void
Delete all key-value from the Map.
map.set1, "111"map.set2, "222"map.size // 2map.clearmap.size // 0
keys(): K[]
return all Map's key.
map.set1, 2map.settrue, falsemap.set, map.keys // [1, true, ["1"]]
values(): V[]
return all Map's value.
map.set1, 2map.settrue, falsemap.set, map.values // [2, false, 'lavyun']
entries(): Array<[K, V]>
return all Map's key-value.
map.set1, 2map.settrue, falsemap.set, map.entries/* [ [1, 2], [true, false], [["1"], {name: 'lavyun'}]]*/
forEach(cb, context?: any): void
Traversal the Map.Accept two parameters, first is a callback, second is a optional context.
callback function accepts 3 optional params,first is value, second is key, last is the map.
map.set1, "111".set2 "222"map.forEach// 1 - '111'// 2 - '222'
You can pass the second param to set the callback's context
map.set1, "111".set2 "222"map.forEach, person// 1 - '111' - 'lavyun'// 2 - '222' - 'lavyun'
Licence
MIT LICENCE