Skip to content

Commit

Permalink
[REF] functions: create helper for COUNTUNIQUE
Browse files Browse the repository at this point in the history
This commit is a step to introduce the spreadsheet pivot. The function
COUNTUNIQUE is used in the pivot table to count the unique values in a
range. The helper function is created to avoid code duplication.

Task: 3748717
Part-of: #4025
Co-authored-by: rrahir <rar@odoo.com>
Co-authored-by: Pierre Rousseau <pro@odoo.com>
  • Loading branch information
pro-odoo and rrahir committed May 15, 2024
1 parent eebad38 commit 51336c1
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 15 deletions.
19 changes: 17 additions & 2 deletions src/functions/helper_math.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,21 @@
import { Arg, Locale } from "../types";
import { reduceNumbers } from "./helpers";
import { Arg, FPayload, Locale } from "../types";
import { reduceAny, reduceNumbers } from "./helpers";

export function isDefined(data: FPayload | undefined): boolean {
if (data === undefined) {
return false;
}
const { value } = data;
if (value === null || value === "") {
return false;
}
return true;
}

export function sum(values: Arg[], locale: Locale): number {
return reduceNumbers(values, (acc, a) => acc + a, 0, locale);
}

export function countUnique(args: Arg[]): number {
return reduceAny(args, (acc, a) => (isDefined(a) ? acc.add(a?.value) : acc), new Set()).size;
}
15 changes: 2 additions & 13 deletions src/functions/module_math.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import {
import { CellErrorType } from "../types/errors";
import { arg } from "./arguments";
import { assertPositive } from "./helper_assert";
import { sum } from "./helper_math";
import { countUnique, isDefined, sum } from "./helper_math";
import { getUnitMatrix } from "./helper_matrices";
import {
assert,
Expand Down Expand Up @@ -520,17 +520,6 @@ export const COUNTIFS = {
// COUNTUNIQUE
// -----------------------------------------------------------------------------

function isDefined(data: FPayload | undefined): boolean {
if (data === undefined) {
return false;
}
const { value } = data;
if (value === null || value === "") {
return false;
}
return true;
}

export const COUNTUNIQUE = {
description: _t("Counts number of unique values in a range."),
args: [
Expand All @@ -542,7 +531,7 @@ export const COUNTUNIQUE = {
],
returns: ["NUMBER"],
compute: function (...args: Arg[]): number {
return reduceAny(args, (acc, a) => (isDefined(a) ? acc.add(a?.value) : acc), new Set()).size;
return countUnique(args);
},
} satisfies AddFunctionDescription;

Expand Down

0 comments on commit 51336c1

Please sign in to comment.