Skip to content

Commit

Permalink
tree-reports: sort by account names
Browse files Browse the repository at this point in the history
  • Loading branch information
yagebu committed Jan 2, 2025
1 parent cde3f06 commit e3096c4
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 7 deletions.
18 changes: 13 additions & 5 deletions frontend/src/charts/hierarchy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ import {
unknown,
} from "../lib/validation";
import { notify_warn } from "../notifications";
import { sort_by_strings } from "../sort";
import type { ChartContext } from "./context";

/** The data provided with a fava.core.tree.SerialisedTreeNode. */
Expand Down Expand Up @@ -86,13 +87,20 @@ export class HierarchyChart {
}
}

const sort_children = (values: AccountTreeNode[]) =>
sort_by_strings(values, (v) => v.account);

const balances = record(number);

export const account_hierarchy_validator: Validator<AccountTreeNode> = object({
account: string,
balance: record(number),
balance_children: record(number),
children: lazy(() => array(account_hierarchy_validator)),
cost: optional(record(number)),
cost_children: optional(record(number)),
balance: balances,
balance_children: balances,
children: lazy(
() => (json) => array(account_hierarchy_validator)(json).map(sort_children),
),
cost: optional(balances),
cost_children: optional(balances),
has_txns: defaultValue(boolean, () => false),
});

Expand Down
14 changes: 12 additions & 2 deletions frontend/src/sort/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,16 @@ export class Sorter<T = unknown> {
}
}

/**
* Sort array with provided string value getter.
*/
export function sort_by_strings<T>(
data: readonly T[],
value: (v: T) => string,
): T[] {
return sort_internal(data, value, compare_strings, 1);
}

/**
* Sort array with provided value getter and compare function.
* Calls the value getter only once per element.
Expand All @@ -70,7 +80,7 @@ function sort_internal<T, U>(
value: (row: T) => U,
compare: (a: U, b: U) => number,
direction: SortDirection,
) {
): T[] {
const indices = Uint32Array.from(data, (_d, i) => i);
const values = data.map(value);
// values and indices are of the same length (as data), so this is safe
Expand Down Expand Up @@ -109,7 +119,7 @@ export class DateColumn<T extends { date: string }> extends NumberColumn<T> {
}
/** A SortColumn for strings. */
export class StringColumn<T> implements SortColumn<T> {
private compare: (x: string, y: string) => number = compare_strings;
private compare = compare_strings;

constructor(
readonly name: string,
Expand Down

0 comments on commit e3096c4

Please sign in to comment.