Skip to content

Commit a1a906e

Browse files
NathanJangflesler
authored andcommitted
Implement ES6 iterator support
1 parent 07ec5c5 commit a1a906e

File tree

3 files changed

+50
-0
lines changed

3 files changed

+50
-0
lines changed

Readme.md

+5
Original file line numberDiff line numberDiff line change
@@ -139,6 +139,11 @@ map
139139
.forEach(function(value, key) {
140140
console.log(key + " : " + value);
141141
});
142+
143+
// ES6 Iterators
144+
for (const pair of map) {
145+
console.log(`${pair.key} : ${pair.value}`)
146+
}
142147
```
143148

144149
## LICENSE

hashmap.js

+18
Original file line numberDiff line numberDiff line change
@@ -175,6 +175,24 @@
175175

176176
HashMap.uid = 0;
177177

178+
// Iterator protocol for ES6
179+
if (typeof Symbol !== 'undefined' && typeof Symbol.iterator !== 'undefined') {
180+
proto[Symbol.iterator] = function() {
181+
var entries = this.entries();
182+
var i = 0;
183+
return {
184+
next:function() {
185+
if (i === entries.length) { return { done: true }; }
186+
var currentEntry = entries[i++];
187+
return {
188+
value: { key: currentEntry[0], value: currentEntry[1] },
189+
done: false
190+
};
191+
}
192+
};
193+
};
194+
}
195+
178196
//- Add chaining to all methods that don't return something
179197

180198
['set','multi','copy','delete','clear','forEach'].forEach(function(method) {

test/test.js

+27
Original file line numberDiff line numberDiff line change
@@ -312,6 +312,33 @@ describe('hashmap', function() {
312312
});
313313
});
314314

315+
describe('ES6 Iterators', function() {
316+
it('should do nothing on an empty hashmap', function() {
317+
var called = false;
318+
for (var pair of hashmap) { // jshint ignore:line
319+
// (`pair` is not used)
320+
called = true;
321+
}
322+
expect(called).to.be.false;
323+
});
324+
325+
it('should iterate over all entries exactly once', function() {
326+
// Since order of iteration is not guaranteed, we'll keep track of which key-value pair has been checked, and how many times.
327+
var numberOfTries = 10;
328+
var calls = new Array(numberOfTries).fill(0);
329+
// Populate hashmap with ['keyI': I] pairs
330+
for (var i = 0; i < numberOfTries; i++) {
331+
hashmap.set('key' + i, i);
332+
}
333+
// Perform ES6 iteration
334+
for (var pair of hashmap) {
335+
expect(pair.key).to.equal('key' + pair.value);
336+
calls[pair.value]++;
337+
}
338+
expect(calls).to.deep.equal(new Array(numberOfTries).fill(1));
339+
});
340+
});
341+
315342
describe('hashmap.count() and hashmap.size', function() {
316343
// NOTE: count() is expected to return .size, this
317344
// will be checked only in this unit test!

0 commit comments

Comments
 (0)