Skip to content

Commit

Permalink
HashMap: allow valueIterable to be iterated more than once (#27)
Browse files Browse the repository at this point in the history
Iterators are stateful and can't be reused.  Therefore, the iterator protocol
makes Iterable's contain a zero-argument function which creates a new iterator,
and re-calls this zero-argument function to create a new iterator every time
an iteration starts.

hamt.values() returns an iterator which is stateful, so it must be wrapped in
a zero-argument function to become an Iterable<T>.
  • Loading branch information
wuzzeb authored and emmanueltouzery committed Jan 22, 2019
1 parent 11a1437 commit addc21f
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 1 deletion.
5 changes: 4 additions & 1 deletion src/HashMap.ts
Original file line number Diff line number Diff line change
Expand Up @@ -227,7 +227,10 @@ export class HashMap<K,V> implements IMap<K,V> {
* to have equality in the generics type)
*/
valueIterable(): Iterable<V> {
return <Iterable<V>>this.hamt.values();
const hamt = this.hamt;
return {
[Symbol.iterator]() { return hamt.values(); }
};
}

/**
Expand Down
5 changes: 5 additions & 0 deletions tests/HashMap.ts
Original file line number Diff line number Diff line change
Expand Up @@ -179,6 +179,11 @@ describe("hashmap extract values", () => {
HashSet.empty<string>().equals(HashSet.ofIterable(HashMap.empty<string,string>().valueIterable()))));
it("should get non-empty valueIterable", () => assert.ok(
HashSet.of("b","d").equals(HashSet.ofIterable(HashMap.empty<string,string>().put("a","b").put("c","d").valueIterable()))));
it("should allow iteration of valueIterable more than once", () => {
const i = HashMap.empty<string, string>().put("a", "b").put("c", "d").valueIterable();
HashSet.of("b", "d").equals(HashSet.ofIterable(Array.from(i)));
HashSet.of("b", "d").equals(HashSet.ofIterable(Array.from(i)));
})
it("supports iterator", () => {
let total = 0;
let letters = [];
Expand Down

0 comments on commit addc21f

Please sign in to comment.