Skip to content

Commit 37fe2f7

Browse files
committed
[PortsJS] Adds hash-table support to PortsJS
1 parent 73d9b0f commit 37fe2f7

File tree

1 file changed

+19
-0
lines changed

1 file changed

+19
-0
lines changed

ports-js/scheme.js

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -266,6 +266,25 @@ function addGlobals(env) {
266266
env.set(Sym('list?'), a => Array.isArray(a));
267267
env.set(Sym('list-ref'), (list, idx) => list[idx]);
268268
env.set(Sym('list-set!'), (list, idx, val) => { list[idx] = val; });
269+
env.set(Sym('make-hash-table'), () => new Map());
270+
env.set(Sym('hash-table?'), x => x instanceof Map);
271+
env.set(Sym('hash-table-set!'), (table, key, value) => {table.set(key, value); null});
272+
env.set(Sym('hash-table-ref'), (...args) => {
273+
const [table, key] = args;
274+
if(args.length === 2) {
275+
if (!table.has(key)) {
276+
throw new Error(`hash-table-ref: Key ${key} not found in hash table`);
277+
}
278+
return table.get(key);
279+
} else if (args.length === 3) {
280+
const defaultValue = args[2];
281+
return table.has(key) ? table.get(key) : defaultValue;
282+
}
283+
284+
});
285+
env.set(Sym('hash-table-delete!'), (table, key) => { table.delete(key); });
286+
env.set(Sym('hash-table-keys'), table => Array.from(table.keys()));
287+
env.set(Sym('hash-table-values'), table => Array.from(table.values()));
269288

270289
// Error handling
271290
env.set(Sym('error'), msg => { throw new Error(msg); });

0 commit comments

Comments
 (0)