Skip to content

Commit fcc2f92

Browse files
ahmedsabiepyu10055
andauthored
Fix flatten implementation on objects (#7059)
BUG Co-authored-by: Ping Yu <[email protected]>
1 parent 087a02a commit fcc2f92

File tree

2 files changed

+35
-2
lines changed

2 files changed

+35
-2
lines changed

tfjs-core/src/util_base.ts

+16-2
Original file line numberDiff line numberDiff line change
@@ -192,12 +192,26 @@ flatten<T extends number|boolean|string|Promise<number>|TypedArray>(
192192
if (result == null) {
193193
result = [];
194194
}
195-
if (Array.isArray(arr) || isTypedArray(arr) && !skipTypedArray) {
195+
if (typeof arr === 'boolean' || typeof arr === 'number' ||
196+
typeof arr === 'string' || isPromise(arr) || arr == null ||
197+
isTypedArray(arr) && skipTypedArray) {
198+
result.push(arr as T);
199+
} else if (Array.isArray(arr) || isTypedArray(arr)) {
196200
for (let i = 0; i < arr.length; ++i) {
197201
flatten(arr[i], result, skipTypedArray);
198202
}
199203
} else {
200-
result.push(arr as T);
204+
let maxIndex = -1;
205+
for (const key of Object.keys(arr)) {
206+
// 0 or positive integer.
207+
if (/^([1-9]+[0-9]*|0)$/.test(key)) {
208+
maxIndex = Math.max(maxIndex, Number(key));
209+
}
210+
}
211+
for (let i = 0; i <= maxIndex; i++) {
212+
// tslint:disable-next-line: no-unnecessary-type-assertion
213+
flatten((arr as RecursiveArray<T>)[i], result, skipTypedArray);
214+
}
201215
}
202216
return result;
203217
}

tfjs-core/src/util_test.ts

+19
Original file line numberDiff line numberDiff line change
@@ -136,6 +136,11 @@ describe('Util', () => {
136136
});
137137

138138
describe('util.flatten', () => {
139+
it('empty', () => {
140+
const data: number[] = [];
141+
expect(util.flatten(data)).toEqual([]);
142+
});
143+
139144
it('nested number arrays', () => {
140145
expect(util.flatten([[1, 2, 3], [4, 5, 6]])).toEqual([1, 2, 3, 4, 5, 6]);
141146
expect(util.flatten([[[1, 2], [3, 4], [5, 6], [7, 8]]])).toEqual([
@@ -169,6 +174,20 @@ describe('util.flatten', () => {
169174
new Uint8Array([7, 8])
170175
]);
171176
});
177+
178+
it('Int8Array', () => {
179+
const data = [new Int8Array([1, 2])];
180+
expect(util.flatten(data)).toEqual([1, 2]);
181+
});
182+
183+
it('index signature', () => {
184+
const data: {[index: number]: number} = {0: 1, 1: 2};
185+
// Will be ignored since array iteration ignores negatives.
186+
data[-1] = -1;
187+
// Will be ignored since non-integer array keys are ignored.
188+
data[3.2] = 4;
189+
expect(util.flatten(data)).toEqual([1, 2]);
190+
});
172191
});
173192

174193
function encodeStrings(a: string[]): Uint8Array[] {

0 commit comments

Comments
 (0)