UNPKG

sussy-util

Version:
84 lines (83 loc) 2.96 kB
import { MapEntry } from '../Types'; import Optional from './Optional'; type Predicate<V, K, C extends Collection<K, V>> = (value: V, key: K, collection: C) => boolean; type Reducer<V, K, C extends Collection<K, V>, U> = (accumulator: U, value: V, key: K, collection: C) => U; type Transformer<V, K, C extends Collection<K, V>, U> = (value: V, key: K, collection: C) => U; export default class Collection<K, V> extends Map<K, V> { /** * Removes the key and value from the map. * @param key - The key of the element to remove. * @returns An Optional containing the removed {key, value}, or empty if not found. */ remove: (key: K) => Optional<MapEntry<K, V>>; /** * Provides a human-readable string representation. */ toString: () => string; /** * Converts the map to an array of {key, value} objects. */ toArray: () => MapEntry<K, V>[]; /** * Returns the number of entries in the Collection. */ count: () => number; /** * Returns true if the key does not exist in the map. */ missing: (key: K) => boolean; /** * Converts the Collection to a JSON string. */ toJSONString: () => string; /** * Checks if the map contains a specific value. */ contains: (value: V) => boolean; /** * Merges entries from another map into this one. */ merge: (map: Map<K, V>) => void; /** * Filters the collection based on a predicate. * Returns a new Collection with entries that satisfy the predicate. */ filter: (predicate: Predicate<V, K, this>) => Collection<K, V>; /** * Transforms the collection values and returns a new Collection with the transformed values. * Keys remain the same. */ mapValues: <U>(transformFn: Transformer<V, K, this, U>) => Collection<K, U>; /** * Maps the collection to an array of values based on a callback function. * Returns an array of transformed values. */ mapArray: <U>(callback: Transformer<V, K, this, U>) => U[]; /** * Reduces the collection into a single value. */ reduce: <U>(reducer: Reducer<V, K, this, U>, initialValue: U) => U; /** * Checks if all entries satisfy the predicate. */ every: (predicate: Predicate<V, K, this>) => boolean; /** * Checks if any entry satisfies the predicate. */ some: (predicate: Predicate<V, K, this>) => boolean; /** * Finds the first entry that satisfies the predicate. * Returns an Optional containing [key, value] if found, otherwise empty. */ find: (predicate: Predicate<V, K, this>) => Optional<[K, V]>; /** * Returns the value as an Optional. */ getOptional: (key: K) => Optional<V>; /** * Finds the key associated with the given value. * Returns an Optional containing the key if found, otherwise empty. */ keyOf: (value: V) => Optional<K>; } export {};