feat: first working version with parameters

This commit is contained in:
2024-04-15 18:46:34 +02:00
parent e29cb11b81
commit 0254bc1ae5
45 changed files with 389 additions and 351 deletions

View File

@ -1,5 +1,20 @@
import { expect, test } from 'vitest'
import { decode, encode } from './flat_tree'
import { decode, encode, concat_encoded } from './flat_tree'
test("it correctly concats nested arrays", () => {
const input_a = encode([1, 2, 3]);
const input_b = 2;
const input_c = encode([4, 5, 6]);
const output = concat_encoded([input_a, input_b, input_c]);
const decoded = decode(output);
expect(decoded[0]).toEqual([1, 2, 3]);
});
// Original test case
test('it correctly decodes/encodes complex nested arrays', () => {
@ -55,7 +70,7 @@ test('it correctly handles sequential nesting', () => {
// If not, you can ignore or remove this test.
test('it correctly handles arrays with mixed data types', () => {
const input = [1, 'text', [true, [null, ['another text']]]];
// @ts-ignore
//@ts-ignore
const decoded = decode(encode(input));
expect(decoded).toEqual(input);
});

View File

@ -1,5 +1,34 @@
type SparseArray<T = number> = (T | T[] | SparseArray<T>)[];
export function concat_encoded(input: (number | number[])[]): number[] {
if (input.length === 1 && Array.isArray(input[0])) {
return input[0]
}
const result = [0, 1]; // opening bracket
let last_closing_bracket = 1;
for (let i = 0; i < input.length; i++) {
const item = input[i];
if (Array.isArray(item)) {
result.push(...item);
if (item.length > 2) {
if (item[item.length - 2] !== 1 && item[item.length - 1] !== 1) {
result.push(1, 1); // add closing bracket if missing
}
}
last_closing_bracket = result.length - 1;
} else {
result[last_closing_bracket]++;
result.push(item);
}
}
return result
}
// Encodes a nested array into a flat array with bracket and distance notation
export function encode(array: SparseArray): number[] {
const encoded = [0, 0]; // Initialize encoded array with root bracket notation
@ -16,7 +45,7 @@ export function encode(array: SparseArray): number[] {
} else {
// Recursively encode non-empty arrays
const child = encode(item);
encoded.push(...child, 1, 0); // Note: The trailing comma after 0 can be removed
encoded.push(...child, 1, 0);
}
// Update missingBracketIndex to the position of the newly added bracket
missingBracketIndex = encoded.length - 1;