dope2/lib/structures/dict.js

36 lines
1.2 KiB
JavaScript

import { RBTreeWrapper } from "../util/rbtree_wrapper.js";
import { indent } from "../util/util.js";
import { newProduct } from "./product.js";
import { newLeft, newRight } from "./sum.js";
// only for debugging
function inspectDict(_depth, options, inspect) {
const entries = [];
this.tree.forEach((key, val) => { entries.push(`${inspect(key, options)} => ${inspect(val, options)}`); });
return `{\n${indent(entries.join(',\n'),2)}\n}`;
}
export const emptyDict = compareFn => RBTreeWrapper.new((x, y) => compareFn(x)(y), inspectDict);
export const has = dict => key => dict.tree.get(key) !== undefined;
export const get = dict => key => dict.tree.get(key);
export const set = dict => key => value => new RBTreeWrapper(dict.tree.remove(key).insert(key, value), inspectDict);
export const remove = dict => key => new RBTreeWrapper(dict.tree.remove(key), inspectDict);
export const length = dict => dict.tree.length;
export const first = dict => dict.tree.begin;
export const last = dict => dict.tree.end;
export const read = iter => {
if (iter !== undefined && iter.valid) {
return newRight(
newProduct(
newProduct(iter.key)(iter.value)
(iter.clone().next())
)
);
}
else {
return newLeft(unit);
}
};