93 lines
1.9 KiB
TypeScript

interface MapPolyfillInterface<K, V> {
set(key: K, value: V): void
get(key: K): V | undefined
delete(key: K): boolean
has(key: K): boolean
clear(): void
forEach(
callback: (value: V, key: K, map: MapPolyfill<K, V>) => void,
thisArg?: any
): void
readonly size: number
}
class MapPolyfill<K, V> implements MapPolyfillInterface<K, V> {
private keys: K[]
private values: V[]
constructor() {
this.keys = []
this.values = []
}
set(key: K, value: V): void {
const index = this.keys.indexOf(key)
if (index === -1) {
this.keys.push(key)
this.values.push(value)
} else {
this.values[index] = value
}
}
get(key: K): V | undefined {
const index = this.keys.indexOf(key)
if (index === -1) {
return undefined
}
return this.values[index]
}
delete(key: K): boolean {
const index = this.keys.indexOf(key)
if (index === -1) {
return false
}
this.keys.splice(index, 1)
this.values.splice(index, 1)
return true
}
has(key: K): boolean {
return this.keys.indexOf(key) !== -1
}
clear(): void {
this.keys = []
this.values = []
}
forEach(
callback: (value: V, key: K, map: MapPolyfill<K, V>) => void,
thisArg?: any
): void {
for (let i = 0; i < this.keys.length; i++) {
callback.call(thisArg, this.values[i], this.keys[i], this)
}
}
get size(): number {
return this.keys.length
}
entries(): IterableIterator<[K, V]> {
let index = 0
const keys = this.keys
const values = this.values
return {
[Symbol.iterator]() {
return this
},
next(): IteratorResult<[K, V]> {
if (index < keys.length) {
return { value: [keys[index], values[index++]], done: false }
} else {
return { value: undefined, done: true }
}
},
}
}
}
export default MapPolyfill