diff --git a/index.js b/index.js index 3d9d162..38b4b0a 100644 --- a/index.js +++ b/index.js @@ -58,9 +58,10 @@ const _Blob = class Blob { * @param {{ type?: string }} [options] */ constructor(blobParts = [], options = {}) { + const parts = []; let size = 0; - const parts = blobParts.map(element => { + for (const element of blobParts) { let part; if (ArrayBuffer.isView(element)) { part = new Uint8Array(element.buffer.slice(element.byteOffset, element.byteOffset + element.byteLength)); @@ -73,8 +74,8 @@ const _Blob = class Blob { } size += ArrayBuffer.isView(part) ? part.byteLength : part.size; - return part; - }); + parts.push(part); + } const type = options.type === undefined ? '' : String(options.type); diff --git a/test.js b/test.js index 48067e8..388bd68 100644 --- a/test.js +++ b/test.js @@ -36,6 +36,41 @@ test('Blob ctor parts', async t => { t.is(await blob.text(), 'abcdefg[object Object]foo='); }); +test('Blob ctor threats an object with @@iterator as a sequence', async t => { + const blob = new Blob({[Symbol.iterator]: Array.prototype[Symbol.iterator]}); + + t.is(blob.size, 0); + t.is(await blob.text(), ''); +}); + +test('Blob ctor reads blob parts from object with @@iterator', async t => { + const input = ['one', 'two', 'three']; + const expected = input.join(''); + + const blob = new Blob({ + * [Symbol.iterator]() { + yield * input; + } + }); + + t.is(blob.size, new TextEncoder().encode(expected).byteLength); + t.is(await blob.text(), expected); +}); + +test('Blob ctor threats a string as a sequence', async t => { + const expected = 'abc'; + const blob = new Blob(expected); + + t.is(await blob.text(), expected); +}); + +test('Blob ctor threats Uint8Array as a sequence', async t => { + const input = [1, 2, 3]; + const blob = new Blob(new Uint8Array(input)); + + t.is(await blob.text(), input.join('')); +}); + test('Blob size', t => { const data = 'a=1'; const blob = new Blob([data]);