UNPKG

standard-data-structures

Version:

A collection of standard data-structures for node and browser

90 lines (89 loc) 2.18 kB
"use strict"; /* tslint:disable strict-comparisons */ Object.defineProperty(exports, "__esModule", { value: true }); const option_1 = require("./option"); /** * An immutable HashMap */ class HashMap { constructor(dict) { this.dict = dict; } /** * Refer [[ICollection.asArray]] */ get asArray() { return this.fold0(new Array(), (v, k, s) => { s.push(v); return s; }); } /** * Refer [[ICollection.isEmpty]] */ get isEmpty() { return this.dict.size === 0; } /** * Creates a new instance of [[HashMap]] */ static of(entries) { return new HashMap(new Map(entries)); } /** * Deletes the provided key from the HashMap */ delete(k) { return this.has(k) ? new HashMap(this.fold0(new Map(), (v0, k0, s) => (k0 === k ? s : s.set(k0, v0)))) : this; } /** * Refer [[ICollection.filter]] */ filter(fn) { return this.fold0(HashMap.of(), (v, k, s) => (fn(v) ? s.set(k, v) : s)); } /** * Refer [[ICollection.fold]] * Use `HasMap.fold0` to fold with keys. */ fold(S, fn) { return this.fold0(S, (v, k, s) => fn(v, s)); } /** * Folds a [[HasMap]] into a value, by calling the function on each key value pair. */ fold0(S, fn) { let s = S; for (const [k, v] of this.dict) { s = fn(v, k, s); } return s; } /** * Returns value for the provided key */ get(k) { return this.dict.has(k) ? option_1.Option.some(this.dict.get(k)) : option_1.Option.none(); } /** * Returns true if the value exists in the HashMap */ has(k) { return this.dict.has(k); } /** * Refer [[ICollection.map]] */ map(ab) { return this.fold0(HashMap.of(), (v, k, S) => S.set(k, ab(v))); } /** * Sets a key value pair and returns a new [[HashMap]]. */ set(k, v) { return new HashMap(this.fold0(new Map([[k, v]]), (v0, k0, s) => k0 === k ? s : s.set(k0, v0))); } } exports.HashMap = HashMap;