104 lines
1.9 KiB
TypeScript
104 lines
1.9 KiB
TypeScript
/**
|
|
* @author Martin Karkowski
|
|
* @email m.karkowski@zema.de
|
|
* @create date 2021-11-23 11:21:57
|
|
* @modify date 2021-11-23 11:21:57
|
|
* @desc [description]
|
|
*/
|
|
|
|
import { rgetattr } from "./objectMethods";
|
|
|
|
const __sentinal = {
|
|
unique: "value",
|
|
};
|
|
|
|
/**
|
|
* Extracts the unique values of an map.
|
|
*
|
|
* @author M.Karkowski
|
|
* @export
|
|
* @template K
|
|
* @template V
|
|
* @param {Map<K, V>} map
|
|
* @return {*} {Set<V>}
|
|
*/
|
|
export function extractUniqueValues<D>(map: Map<any, any>, path = ""): Set<D> {
|
|
return new Set(extractValues(map, path));
|
|
}
|
|
|
|
export function extractValues<D, K>(map: Map<K, any>, path = ""): Array<D> {
|
|
const s = new Array<D>();
|
|
|
|
for (const v of map.values()) {
|
|
if (path) {
|
|
const data: D | typeof __sentinal = rgetattr(v, path, __sentinal);
|
|
if (data !== __sentinal) {
|
|
if (Array.isArray(data)) {
|
|
data.map((item) => s.push(item));
|
|
} else {
|
|
s.push(data as D);
|
|
}
|
|
}
|
|
} else {
|
|
s.push(v as any as D);
|
|
}
|
|
}
|
|
|
|
return s;
|
|
}
|
|
|
|
/**
|
|
*
|
|
*
|
|
* @author M.Karkowski
|
|
* @export
|
|
* @template D
|
|
* @template K
|
|
* @param {Map<K, any>} map
|
|
* @param {string} [path=""]
|
|
* @return {*} {Map<K, D>}
|
|
*/
|
|
export function transformValues<D, K = any>(
|
|
map: Map<K, any>,
|
|
path = ""
|
|
): Map<K, D> {
|
|
const m = new Map<K, D>();
|
|
|
|
for (const [k, v] of map.entries()) {
|
|
if (path) {
|
|
const data: D | typeof __sentinal = rgetattr(v, path, __sentinal);
|
|
if (data !== __sentinal) {
|
|
m.set(k, data as D);
|
|
}
|
|
} else {
|
|
m.set(k, v as any as D);
|
|
}
|
|
}
|
|
|
|
return m;
|
|
}
|
|
|
|
/**
|
|
* Reverses the given map.
|
|
*
|
|
* @author M.Karkowski
|
|
* @export
|
|
* @template K
|
|
* @template V
|
|
* @param {Map<K, V>} map
|
|
* @return {*} {Map<V, Set<K>>}
|
|
*/
|
|
export function reverse<K, V>(map: Map<K, V>): Map<V, Set<K>> {
|
|
const m = new Map<V, Set<K>>();
|
|
|
|
for (const [k, v] of map.entries()) {
|
|
if (!m.has(v)) {
|
|
m.set(v, new Set());
|
|
}
|
|
|
|
m.get(v).add(k);
|
|
}
|
|
|
|
return m;
|
|
}
|