js-slang
Version:
Javascript-based implementations of Source, written in Typescript
96 lines • 2.7 kB
JavaScript
Object.defineProperty(exports, "__esModule", { value: true });
exports.arrayMapFrom = exports.ArrayMap = void 0;
/**
* Python style dictionary
*/
class Dict {
constructor(internalMap = new Map()) {
this.internalMap = internalMap;
}
get size() {
return this.internalMap.size;
}
[Symbol.iterator]() {
return this.internalMap[Symbol.iterator]();
}
get(key) {
return this.internalMap.get(key);
}
set(key, value) {
return this.internalMap.set(key, value);
}
has(key) {
return this.internalMap.has(key);
}
/**
* Similar to how the python dictionary's setdefault function works:
* If the key is not present, it is set to the given value, then that value is returned
* Otherwise, `setdefault` returns the value stored in the dictionary without
* modifying it
*/
setdefault(key, value) {
if (!this.has(key)) {
this.set(key, value);
}
return this.get(key);
}
update(key, defaultVal, updater) {
const value = this.setdefault(key, defaultVal);
const newValue = updater(value);
this.set(key, newValue);
return newValue;
}
entries() {
return [...this.internalMap.entries()];
}
forEach(func) {
this.internalMap.forEach((v, k) => func(k, v));
}
/**
* Similar to `mapAsync`, but for an async mapping function that does not return any value
*/
async forEachAsync(func) {
await Promise.all(this.map((key, value, i) => func(key, value, i)));
}
map(func) {
return this.entries().map(([k, v], i) => func(k, v, i));
}
/**
* Using a mapping function that returns a promise, transform a map
* to another map with different keys and values. All calls to the mapping function
* execute asynchronously
*/
mapAsync(func) {
return Promise.all(this.map((key, value, i) => func(key, value, i)));
}
flatMap(func) {
return this.entries().flatMap(([k, v], i) => func(k, v, i));
}
}
exports.default = Dict;
/**
* Convenience class for maps that store an array of values
*/
class ArrayMap extends Dict {
add(key, item) {
this.setdefault(key, []).push(item);
}
}
exports.ArrayMap = ArrayMap;
function arrayMapFrom(pairs) {
const res = new ArrayMap();
for (const [k, v] of pairs) {
if (Array.isArray(v)) {
for (const each of v) {
res.add(k, each);
}
}
else {
res.add(k, v);
}
}
return res;
}
exports.arrayMapFrom = arrayMapFrom;
//# sourceMappingURL=dict.js.map
;