@liberquack/utils
Version:
Quack utilities
105 lines (103 loc) • 3.08 kB
TypeScript
/// <reference lib="es2020" />
import { Dictionary } from "./types.js";
import { UnionToIntersection } from "utility-types";
export declare function listToDictionary<T>(list: T[], key: keyof T): Dictionary<T>;
export declare function dictionaryToList<T>(dict: Dictionary<T>): T[];
export declare function dictionaryForEach<T>(dict: Dictionary<T>, cb: (entry: T, key: string) => void): void;
/**
* Generates a new dictionary from the original
*
* @example
* dictionaryMap({a: 1, b: 2}, (key, value) => [value, key])
* // {1: "a", 2: "b"}
*
* @param dict
* @param cb
*/
export declare function dictionaryMap<T, R = any>(dict: Dictionary<T>, cb: (key: string, value: T, index: number) => [string, R]): Dictionary<R>;
/**
* Returns a list for each entry
*
* @example
* dictionaryMap({a: 1, b: 2}, (value, key) => value + key)
* // ["a1", "b2"]
*
* @param dict
* @param cb
*/
export declare function dictionaryMapList<T, R>(dict: Dictionary<T>, cb: (key: string, value: T, index: number) => R): R[];
/**
* Reduce values of the dictionary
*
* @example key
* let list = [{gender: M, id: 1}, {gender: M, id: 2}, {gender: F, id: 3}]
* listToDictionaryAcc(list, "gender")
*
* // Result:
* // {
* // M: [
* // {gender: M, id: 1},
* // {gender: M, id: 2}
* // ],
* // F: [
* // {gender: F, id: 3}
* // ]
* // }
*
* @param list
* @param key
*/
export declare function listToDictionaryAcc<T>(list: T[], key: keyof T): Dictionary<T[]>;
/**
* Reduce values of the dictionary
*
*
* @example predicate
* let list = [{gender: M, id: 1}, {gender: M, id: 2}, {gender: F, id: 3}]
* let predicate = (item) => item.id % 2
* listToDictionaryPartitioner(["even","odd"], list, predicate)
*
* // Result:
* // {
* // "even": [
* // {gender: M, id: 1},
* // {gender: M, id: 2}
* // ],
* // "odd": [
* // {gender: F, id: 3}
* // ]
* // }
*
* @param list
* @param partitions
* @param predicate
*/
export declare function listToDictionaryPartitioner<T, R extends string>(list: T[], partitions: R[], predicate: ((item: T) => number)): Record<R | "undefined", T[]>;
/**
* Accumulate dictionary list, resulting a new dictionary of lists
* @example
* let list = [
* {a: 5},
* {a: 5},
* {b: 10},
* ]
* listToDictionaryMergedKeys(list)
* // {a: [5,5], b:[10]}
*
* @param list
*/
export declare function listToDictionaryMergedKeys<T, U = UnionToIntersection<T>, Result = {
[P in keyof U]: U[keyof U][];
}>(list: T[]): Result;
/**
* Reduce dictionary values
* @example
* let dict = {a: 10, b: 20}
* dictionaryAcc(dict, 0, (acc, value: number, key: string) => acc + value)
* //30
*
* @param dict
* @param acc
* @param reducer
*/
export declare function dictionaryAcc<T, Y>(dict: Dictionary<T>, acc: Y, reducer: (acc: Y, item: T, key: string) => Y): Y;