Skip to content

Allow usage of iterable object in Blob constructor. #108

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 4 additions & 3 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -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));
Expand All @@ -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);

Expand Down
35 changes: 35 additions & 0 deletions test.js
Original file line number Diff line number Diff line change
Expand Up @@ -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]);
Expand Down