avm99963 | 37601bc | 2022-02-21 10:36:45 +0100 | [diff] [blame] | 1 | // 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). |
| 4 | export 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ínez | ac2a561 | 2022-12-27 21:51:40 +0100 | [diff] [blame] | 14 | |
| 15 | // The inverse function. |
| 16 | export 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ínez | b47ec06 | 2023-01-15 17:43:26 +0100 | [diff] [blame] | 23 | |
| 24 | let object = []; |
Adrià Vilanova Martínez | ac2a561 | 2022-12-27 21:51:40 +0100 | [diff] [blame] | 25 | for (let i = 0; i < input.length; ++i) { |
Adrià Vilanova Martínez | b47ec06 | 2023-01-15 17:43:26 +0100 | [diff] [blame] | 26 | object[i] = inverseCorrectArrayKeys(input[i]); |
Adrià Vilanova Martínez | ac2a561 | 2022-12-27 21:51:40 +0100 | [diff] [blame] | 27 | } |
Adrià Vilanova Martínez | b47ec06 | 2023-01-15 17:43:26 +0100 | [diff] [blame] | 28 | return object; |
Adrià Vilanova Martínez | ac2a561 | 2022-12-27 21:51:40 +0100 | [diff] [blame] | 29 | } |
| 30 | |
| 31 | if (typeof input !== 'object' || input === null) return input; |
| 32 | |
Adrià Vilanova Martínez | b47ec06 | 2023-01-15 17:43:26 +0100 | [diff] [blame] | 33 | 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ínez | ac2a561 | 2022-12-27 21:51:40 +0100 | [diff] [blame] | 39 | Object.entries(input).forEach(entry => { |
| 40 | array[entry[0] - 1] = inverseCorrectArrayKeys(entry[1]); |
| 41 | }); |
| 42 | return array; |
| 43 | } |