Skip to content
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

Fix flatten implementation on objects #7059

Merged
merged 4 commits into from Nov 29, 2022
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
18 changes: 16 additions & 2 deletions tfjs-core/src/util_base.ts
Expand Up @@ -192,12 +192,26 @@ flatten<T extends number|boolean|string|Promise<number>|TypedArray>(
if (result == null) {
result = [];
}
if (Array.isArray(arr) || isTypedArray(arr) && !skipTypedArray) {
if (typeof arr === 'boolean' || typeof arr === 'number' ||
typeof arr === 'string' || isPromise(arr) || arr == null ||
isTypedArray(arr) && skipTypedArray) {
result.push(arr as T);
} else if (Array.isArray(arr) || isTypedArray(arr)) {
for (let i = 0; i < arr.length; ++i) {
flatten(arr[i], result, skipTypedArray);
}
} else {
result.push(arr as T);
let maxIndex = -1;
for (const key of Object.keys(arr)) {
// 0 or positive integer.
if (/^([1-9]+[0-9]*|0)$/.test(key)) {
maxIndex = Math.max(maxIndex, Number(key));
}
}
for (let i = 0; i <= maxIndex; i++) {
// tslint:disable-next-line: no-unnecessary-type-assertion
flatten((arr as RecursiveArray<T>)[i], result, skipTypedArray);
}
}
return result;
}
Expand Down
19 changes: 19 additions & 0 deletions tfjs-core/src/util_test.ts
Expand Up @@ -136,6 +136,11 @@ describe('Util', () => {
});

describe('util.flatten', () => {
it('empty', () => {
const data: number[] = [];
expect(util.flatten(data)).toEqual([]);
});

it('nested number arrays', () => {
expect(util.flatten([[1, 2, 3], [4, 5, 6]])).toEqual([1, 2, 3, 4, 5, 6]);
expect(util.flatten([[[1, 2], [3, 4], [5, 6], [7, 8]]])).toEqual([
Expand Down Expand Up @@ -169,6 +174,20 @@ describe('util.flatten', () => {
new Uint8Array([7, 8])
]);
});

it('Int8Array', () => {
const data = [new Int8Array([1, 2])];
expect(util.flatten(data)).toEqual([1, 2]);
});

it('index signature', () => {
const data: {[index: number]: number} = {0: 1, 1: 2};
// Will be ignored since array iteration ignores negatives.
data[-1] = -1;
// Will be ignored since non-integer array keys are ignored.
data[3.2] = 4;
expect(util.flatten(data)).toEqual([1, 2]);
});
});

function encodeStrings(a: string[]): Uint8Array[] {
Expand Down