Skip to content

Commit

Permalink
feat: Add functions sum() and avg() to DataArray (#2351)
Browse files Browse the repository at this point in the history
  • Loading branch information
carlesalbasboix authored Jun 8, 2024
1 parent d05d6d6 commit 75c38b9
Show file tree
Hide file tree
Showing 3 changed files with 32 additions and 0 deletions.
6 changes: 6 additions & 0 deletions docs/docs/api/data-array.md
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,12 @@ export interface DataArray<T> {
/** Run a lambda on each element in the array. */
forEach(f: ArrayFunc<T, void>): void;

/** Calculate the sum of the elements of the array. */
sum(): number;

/** Calculate the average of the elements of the array. */
avg(): number | undefined;

/** Convert this to a plain javascript array. */
array(): T[];

Expand Down
16 changes: 16 additions & 0 deletions src/api/data-array.ts
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,12 @@ export interface DataArray<T> {
/** Run a lambda on each element in the array. */
forEach(f: ArrayFunc<T, void>): void;

/** Calculate the sum of the elements of the array. */
sum(): number;

/** Calculate the average of the elements of the array. */
avg(): number | undefined;

/** Convert this to a plain javascript array. */
array(): T[];

Expand Down Expand Up @@ -164,6 +170,8 @@ class DataArrayImpl<T> implements DataArray<T> {
"defaultComparator",
"toString",
"settings",
"sum",
"avg"
]);

private static ARRAY_PROXY: ProxyHandler<DataArrayImpl<any>> = {
Expand Down Expand Up @@ -446,6 +454,14 @@ class DataArrayImpl<T> implements DataArray<T> {
}
}

public sum() {
return this.values.reduce((a, b) => a + b, 0);
}

public avg() {
return this.sum() / this.values.length;
}

public array(): T[] {
return ([] as any[]).concat(this.values);
}
Expand Down
10 changes: 10 additions & 0 deletions src/test/api/data-array.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -179,6 +179,16 @@ describe("last", () => {
test("nonempty", () => expect(da([1, 2, 3]).last()).toEqual(3));
});

describe("sum", () => {
test("empty", () => expect(da([]).sum()).toEqual(0));
test("numbers", () => expect(da([1, 10, 2]).sum()).toEqual(13));
});

describe("avg", () => {
test("empty", () => expect(da([]).avg()).toEqual(NaN));
test("numbers", () => expect(da([5, 10, 15]).avg()).toEqual(10));
});

/** Utility function for quickly creating a data array. */
function da<T>(val: T[]): DataArray<T> {
return DataArray.wrap(val, DEFAULT_QUERY_SETTINGS);
Expand Down

0 comments on commit 75c38b9

Please sign in to comment.