import { reduce } from "lodash";
import { is_array, is_object } from "./type-checking";
function map_comp_fn(func, fallback) {
return (a, b) => {
const c = {};
if (typeof b === "number") {
for (let k in a) {
let v = a[k];
c[k] = func(v, b);
}
} else {
for (let k in a) {
let v = a[k];
c[k] = func(v, b[k] ?? fallback);
}
}
return c;
};
}
export const map_limit = map_comp_fn(Math.min, Number.MAX_VALUE);
export const map_min = map_limit;
export const map_max = map_comp_fn(Math.max, Number.MIN_VALUE);
export function sum(arr, start = 0) {
if (start == null) {
start = 0;
}
return reduce(arr, (a, b) => a + b, start);
}
export function is_zero_map(map: undefined | null | object): boolean {
if (map == null) {
return true;
}
for (let k in map) {
if (map[k]) {
return false;
}
}
return true;
}
export function map_without_undefined_and_null(map?: object): object | undefined | null {
if (map == null) {
return;
}
if (is_array(map)) {
return map;
}
const new_map = {};
for (let k in map) {
const v = map[k];
if (v == null) {
continue;
} else {
new_map[k] = is_object(v) ? map_without_undefined_and_null(v) : v;
}
}
return new_map;
}
export function map_mutate_out_undefined_and_null(map: object): void {
for (let k in map) {
const v = map[k];
if (v == null) {
delete map[k];
}
}
}