blob: c618cec0033e760c3966180cd215a00854e657c6 [file] [log] [blame]
avm9996337601bc2022-02-21 10:36:45 +01001// Function which converts a protobuf array into an array which can be accessed
2// as if it was a protobuf object (with the same keys). If the input is not an
3// array it returns itself (since it is called recursively).
4export function correctArrayKeys(input) {
5 if (!Array.isArray(input)) return input;
6
7 let object = [];
8 for (let i = 0; i < input.length; ++i) {
9 if (input[i] === null) continue;
10 object[i + 1] = correctArrayKeys(input[i]);
11 }
12 return object;
13}
Adrià Vilanova Martínezac2a5612022-12-27 21:51:40 +010014
15// The inverse function.
16export function inverseCorrectArrayKeys(input) {
17 if (Array.isArray(input)) {
18 if (input[0] === null || input[0] === undefined) {
19 // Make a copy of the input array so we don't modify the original one.
20 input = Array.from(input);
21 input.shift();
22 }
Adrià Vilanova Martínezb47ec062023-01-15 17:43:26 +010023
24 let object = [];
Adrià Vilanova Martínezac2a5612022-12-27 21:51:40 +010025 for (let i = 0; i < input.length; ++i) {
Adrià Vilanova Martínezb47ec062023-01-15 17:43:26 +010026 object[i] = inverseCorrectArrayKeys(input[i]);
Adrià Vilanova Martínezac2a5612022-12-27 21:51:40 +010027 }
Adrià Vilanova Martínezb47ec062023-01-15 17:43:26 +010028 return object;
Adrià Vilanova Martínezac2a5612022-12-27 21:51:40 +010029 }
30
31 if (typeof input !== 'object' || input === null) return input;
32
Adrià Vilanova Martínezb47ec062023-01-15 17:43:26 +010033 const keys = Object.keys(input);
34 if (keys.length === 0) return [];
35
36 const maxItem = Math.max(...keys);
37 let array = Array(maxItem).fill(undefined);
38
Adrià Vilanova Martínezac2a5612022-12-27 21:51:40 +010039 Object.entries(input).forEach(entry => {
40 array[entry[0] - 1] = inverseCorrectArrayKeys(entry[1]);
41 });
42 return array;
43}