Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place.
Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place.
Path: blob/master/src/packages/util/maps.ts
Views: 687
/*1* This file is part of CoCalc: Copyright © 2020 Sagemath, Inc.2* License: MS-RSL – see LICENSE.md for details3*/45import { reduce } from "lodash";6import { is_array, is_object } from "./type-checking";78// compare the values in a map a by the values of b9// or just by b if b is a number, using func(a, b)10function map_comp_fn(func, fallback) {11return (a, b) => {12const c = {};13if (typeof b === "number") {14for (let k in a) {15let v = a[k];16c[k] = func(v, b);17}18} else {19for (let k in a) {20let v = a[k];21c[k] = func(v, b[k] ?? fallback);22}23}24return c;25};26}2728export const map_limit = map_comp_fn(Math.min, Number.MAX_VALUE);29export const map_min = map_limit;30export const map_max = map_comp_fn(Math.max, Number.MIN_VALUE);3132// arithmetic sum of an array33export function sum(arr, start = 0) {34if (start == null) {35start = 0;36}37return reduce(arr, (a, b) => a + b, start);38}3940// returns true if the given map is undefined or empty, or all the values are falsy41export function is_zero_map(map: undefined | null | object): boolean {42if (map == null) {43return true;44}45for (let k in map) {46if (map[k]) {47return false;48}49}50return true;51}5253// Returns copy of map with no undefined/null values (recursive).54// Doesn't modify map. If map is an array, just returns it55// with no change even if it has undefined values.56export function map_without_undefined_and_null(map?: object): object | undefined | null {57if (map == null) {58return;59}60if (is_array(map)) {61return map;62}63const new_map = {};64for (let k in map) {65const v = map[k];66if (v == null) {67continue;68} else {69new_map[k] = is_object(v) ? map_without_undefined_and_null(v) : v;70}71}72return new_map;73}7475// modify map in places deleting keys with null or undefined76// values; NOT recursive.77export function map_mutate_out_undefined_and_null(map: object): void {78for (let k in map) {79const v = map[k];80if (v == null) {81delete map[k];82}83}84}858687