Add array concat util (#9306)

pull/28217/head
Michael Weimann 2022-09-21 20:06:05 +02:00 committed by GitHub
parent c182c1c706
commit 516b4f0ff8
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 39 additions and 4 deletions

View File

@ -18,6 +18,7 @@ import { IEncryptedFile, MatrixClient } from "matrix-js-sdk/src/matrix";
import { SimpleObservable } from "matrix-widget-api";
import { uploadFile } from "../ContentMessages";
import { concat } from "../utils/arrays";
import { IDestroyable } from "../utils/IDestroyable";
import { Singleflight } from "../utils/Singleflight";
import { Playback } from "./Playback";
@ -148,10 +149,7 @@ export class VoiceMessageRecording implements IDestroyable {
private onDataAvailable = (data: ArrayBuffer) => {
const buf = new Uint8Array(data);
const newBuf = new Uint8Array(this.buffer.length + buf.length);
newBuf.set(this.buffer, 0);
newBuf.set(buf, this.buffer.length);
this.buffer = newBuf;
this.buffer = concat(this.buffer, buf);
};
private get audioBuffer(): Uint8Array {

View File

@ -304,3 +304,12 @@ export class GroupedArray<K, T> {
return new ArrayUtil(a);
}
}
export const concat = (...arrays: Uint8Array[]): Uint8Array => {
return arrays.reduce((concatenatedSoFar: Uint8Array, toBeConcatenated: Uint8Array) => {
const concatenated = new Uint8Array(concatenatedSoFar.length + toBeConcatenated.length);
concatenated.set(concatenatedSoFar, 0);
concatenated.set(toBeConcatenated, concatenatedSoFar.length);
return concatenated;
}, new Uint8Array(0));
};

View File

@ -28,6 +28,7 @@ import {
arrayIntersection,
ArrayUtil,
GroupedArray,
concat,
} from "../../src/utils/arrays";
type TestParams = { input: number[], output: number[] };
@ -375,5 +376,32 @@ describe('arrays', () => {
expect(result.value).toEqual(output);
});
});
describe("concat", () => {
const emptyArray = () => new Uint8Array(0);
const array1 = () => new Uint8Array([1, 2, 3]);
const array2 = () => new Uint8Array([4, 5, 6]);
const array3 = () => new Uint8Array([7, 8, 9]);
it("should work for empty arrays", () => {
expect(concat(emptyArray(), emptyArray())).toEqual(emptyArray());
});
it("should concat an empty and non-empty array", () => {
expect(concat(emptyArray(), array1())).toEqual(array1());
});
it("should concat an non-empty and empty array", () => {
expect(concat(array1(), emptyArray())).toEqual(array1());
});
it("should concat two arrays", () => {
expect(concat(array1(), array2())).toEqual(new Uint8Array([1, 2, 3, 4, 5, 6]));
});
it("should concat three arrays", () => {
expect(concat(array1(), array2(), array3())).toEqual(new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8, 9]));
});
});
});