shrimp/src/prelude/dict.ts
2025-10-29 13:26:04 -07:00

36 lines
1.5 KiB
TypeScript

import { type Value, toString, toValue } from 'reefvm'
export const dict = {
keys: (dict: Record<string, any>) => Object.keys(dict),
values: (dict: Record<string, any>) => Object.values(dict),
entries: (dict: Record<string, any>) => Object.entries(dict).map(([k, v]) => ({ key: k, value: v })),
'has?': (dict: Record<string, any>, key: string) => key in dict,
get: (dict: Record<string, any>, key: string, defaultValue: any = null) => dict[key] ?? defaultValue,
set: (dict: Value, key: Value, value: Value) => {
const map = dict.value as Map<string, Value>
map.set(toString(key), value)
return dict
},
merge: (...dicts: Record<string, any>[]) => Object.assign({}, ...dicts),
'empty?': (dict: Record<string, any>) => Object.keys(dict).length === 0,
map: async (dict: Record<string, any>, cb: Function) => {
const result: Record<string, any> = {}
for (const [key, value] of Object.entries(dict)) {
result[key] = await cb(value, key)
}
return result
},
filter: async (dict: Record<string, any>, cb: Function) => {
const result: Record<string, any> = {}
for (const [key, value] of Object.entries(dict)) {
if (await cb(value, key)) result[key] = value
}
return result
},
'from-entries': (entries: [string, any][]) => Object.fromEntries(entries),
}
// raw functions deal directly in Value types, meaning we can modify collection
// careful - they MUST return a Value!
; (dict.set as any).raw = true