Skip to content

Commit

Permalink
array: defaultComparator, noFail option for sort
Browse files Browse the repository at this point in the history
  • Loading branch information
hbbio committed Jul 25, 2024
1 parent 173791d commit b5a12a7
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 6 deletions.
38 changes: 33 additions & 5 deletions src/array.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
import { type AnyCell, type MapCell, ValueCell } from "./cell";
import type { AnyCell, MapCell, ValueCell } from "./cell";
import { collector, reuseOrCreate } from "./gc";
import type { SheetProxy } from "./proxy";

export type CellArray<T> = AnyCell<AnyCell<T>[]>;
export type ValueCellArray<T> = ValueCell<ValueCell<T>[]>;

/**
* mapArray implements .map() for a cellified array.
Expand Down Expand Up @@ -53,20 +54,45 @@ export const mapArray = <T, U>(
name
);

/**
* Compares two values and returns a number indicating their order.
*
* This function is designed to be used as a comparator in sorting functions.
* It returns:
* - `1` if `a` is greater than `b`
* - `-1` if `a` is less than `b`
* - `0` if `a` is equal to `b`
*
* @param {*} a - The first value to compare.
* @param {*} b - The second value to compare.
* @returns {number} - Order.
*
* @example
* const array = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5];
* array.sort(defaultComparator);
*/
export const defaultComparator = <T>(a: T, b: T): number =>
a > b ? 1 : a < b ? -1 : 0;

/**
* implementation of sort for a cellified array.
* @description this implementation relies on pointers but reuses the original cells.
* @param proxy
* @param arr
* @param compare comparison function
* @param noFail should be true when the following conditions are met:
* 1. compare must be defined
* 2. cells must be an array (possibly empty)
* 3. compare should never fail
*/
export const sort = <T>(
proxy: SheetProxy,
arr: CellArray<T>,
compare: (a: T, b: T) => number = (a, b) => (a > b ? 1 : a < b ? -1 : 0)
compare: (a: T, b: T) => number = defaultComparator,
noFail = false
): CellArray<T> => {
const coll = collector<CellArray<T>>(proxy);
return proxy.map(
return proxy.mapNoPrevious(
[arr],
(cells) =>
coll(
Expand All @@ -77,10 +103,12 @@ export const sort = <T>(
.map((_, index) => index)
.sort((indexA, indexB) => compare(_cells[indexA], _cells[indexB]))
.map((index) => cells[index]),
"_sort"
"_sort",
noFail
)
),
"sort"
"sort",
noFail
);
};

Expand Down
4 changes: 3 additions & 1 deletion src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ export type { ComputeFn, Unsubscriber } from "./types";
// Utilities

export {
defaultComparator,
filter,
filterPredicateCell,
find,
Expand All @@ -38,7 +39,8 @@ export {
mapArrayCell,
reduce,
sort,
type CellArray
type CellArray,
type ValueCellArray
} from "./array";
export {
cellify,
Expand Down

0 comments on commit b5a12a7

Please sign in to comment.