blob: a2e2d06998554195047cc52055a928621896683c [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 }
23 for (let i = 0; i < input.length; ++i) {
24 input[i] = inverseCorrectArrayKeys(input[i]);
25 }
26 return input;
27 }
28
29 if (typeof input !== 'object' || input === null) return input;
30
31 let array = [];
32 Object.entries(input).forEach(entry => {
33 array[entry[0] - 1] = inverseCorrectArrayKeys(entry[1]);
34 });
35 return array;
36}