Skip to content

Commit c2903ca

Browse files
authored
Allow usage of iterable object in Blob constructor. (#108)
* Allow usage of iterable object in Blob constructor. * Fix ESLint errors
1 parent 0b02843 commit c2903ca

File tree

2 files changed

+39
-3
lines changed

2 files changed

+39
-3
lines changed

index.js

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -58,9 +58,10 @@ const _Blob = class Blob {
5858
* @param {{ type?: string }} [options]
5959
*/
6060
constructor(blobParts = [], options = {}) {
61+
const parts = [];
6162
let size = 0;
6263

63-
const parts = blobParts.map(element => {
64+
for (const element of blobParts) {
6465
let part;
6566
if (ArrayBuffer.isView(element)) {
6667
part = new Uint8Array(element.buffer.slice(element.byteOffset, element.byteOffset + element.byteLength));
@@ -73,8 +74,8 @@ const _Blob = class Blob {
7374
}
7475

7576
size += ArrayBuffer.isView(part) ? part.byteLength : part.size;
76-
return part;
77-
});
77+
parts.push(part);
78+
}
7879

7980
const type = options.type === undefined ? '' : String(options.type);
8081

test.js

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,41 @@ test('Blob ctor parts', async t => {
3636
t.is(await blob.text(), 'abcdefg[object Object]foo=');
3737
});
3838

39+
test('Blob ctor threats an object with @@iterator as a sequence', async t => {
40+
const blob = new Blob({[Symbol.iterator]: Array.prototype[Symbol.iterator]});
41+
42+
t.is(blob.size, 0);
43+
t.is(await blob.text(), '');
44+
});
45+
46+
test('Blob ctor reads blob parts from object with @@iterator', async t => {
47+
const input = ['one', 'two', 'three'];
48+
const expected = input.join('');
49+
50+
const blob = new Blob({
51+
* [Symbol.iterator]() {
52+
yield * input;
53+
}
54+
});
55+
56+
t.is(blob.size, new TextEncoder().encode(expected).byteLength);
57+
t.is(await blob.text(), expected);
58+
});
59+
60+
test('Blob ctor threats a string as a sequence', async t => {
61+
const expected = 'abc';
62+
const blob = new Blob(expected);
63+
64+
t.is(await blob.text(), expected);
65+
});
66+
67+
test('Blob ctor threats Uint8Array as a sequence', async t => {
68+
const input = [1, 2, 3];
69+
const blob = new Blob(new Uint8Array(input));
70+
71+
t.is(await blob.text(), input.join(''));
72+
});
73+
3974
test('Blob size', t => {
4075
const data = 'a=1';
4176
const blob = new Blob([data]);

0 commit comments

Comments
 (0)