Skip to content

Commit

Permalink
Make Headers iterable
Browse files Browse the repository at this point in the history
Closes #127, #174.
  • Loading branch information
TimothyGu committed Oct 8, 2016
1 parent 78c5ba7 commit f8a6bcc
Show file tree
Hide file tree
Showing 2 changed files with 129 additions and 0 deletions.
70 changes: 70 additions & 0 deletions src/headers.js
Original file line number Diff line number Diff line change
Expand Up @@ -135,4 +135,74 @@ export default class Headers {
raw() {
return this[MAP];
}

/**
* Get an iterator on keys.
*
* @return Iterator
*/
keys() {
const keys = [];
this.forEach((_, name) => keys.push(name));
return new Iterator(keys);
}

/**
* Get an iterator on values.
*
* @return Iterator
*/
values() {
const values = [];
this.forEach(value => values.push(value));
return new Iterator(values);
}

/**
* Get an iterator on entries.
*
* @return Iterator
*/
entries() {
const entries = [];
this.forEach((value, name) => entries.push([name, value]));
return new Iterator(entries);
}

/**
* Get an iterator on entries.
*
* This is the default iterator of the Headers object.
*
* @return Iterator
*/
[Symbol.iterator]() {
return this.entries();
}
}

const ITEMS = Symbol('items');
class Iterator {
constructor(items) {
this[ITEMS] = items;
}

next() {
if (!this[ITEMS].length) {
return {
value: undefined,
done: true
};
}

return {
value: this[ITEMS].shift(),
done: false
};

}

[Symbol.iterator]() {
return this;
}
}
59 changes: 59 additions & 0 deletions test/test.js
Original file line number Diff line number Diff line change
Expand Up @@ -1131,6 +1131,65 @@ describe('node-fetch', function() {
expect(result).to.deep.equal(expected);
});

it('should allow iterating through all headers', function() {
var headers = new Headers({
a: 1
, b: [2, 3]
, c: [4]
});
expect(headers).to.have.property(Symbol.iterator);
expect(headers).to.have.property('keys');
expect(headers).to.have.property('values');
expect(headers).to.have.property('entries');

var result, expected;

result = [];
for (let [key, val] of headers) {
result.push([key, val]);
}

expected = [
["a", "1"]
, ["b", "2"]
, ["b", "3"]
, ["c", "4"]
];
expect(result).to.deep.equal(expected);

result = [];
for (let [key, val] of headers.entries()) {
result.push([key, val]);
}
expect(result).to.deep.equal(expected);

result = [];
for (let key of headers.keys()) {
result.push(key);
}

expected = [
"a"
, "b"
, "b"
, "c"
];
expect(result).to.deep.equal(expected);

result = [];
for (let key of headers.values()) {
result.push(key);
}

expected = [
"1"
, "2"
, "3"
, "4"
];
expect(result).to.deep.equal(expected);
});

it('should allow deleting header', function() {
url = base + '/cookie';
return fetch(url).then(function(res) {
Expand Down

0 comments on commit f8a6bcc

Please sign in to comment.