Skip to content

Commit

Permalink
feat: create xyFilter
Browse files Browse the repository at this point in the history
  • Loading branch information
lpatiny committed Oct 13, 2023
1 parent 570147c commit 223f6f3
Show file tree
Hide file tree
Showing 3 changed files with 69 additions and 0 deletions.
35 changes: 35 additions & 0 deletions src/xy/__tests__/xyFilter.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import { xyFilter } from '../../index';

describe('xyFilter', () => {
const x = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const y = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11];
const points = { x, y };

it('no filter', () => {
const result = xyFilter(points);
expect(result).toStrictEqual({
x: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
y: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11],
});
});

it('x filter', () => {
const result = xyFilter(points, {
filter: (xValue) => xValue <= 2 || xValue >= 5,
});
expect(result).toStrictEqual({
x: [0, 1, 2, 5, 6, 7, 8, 9, 10],
y: [1, 2, 3, 6, 7, 8, 9, 10, 11],
});
});

it('y filter', () => {
const result = xyFilter(points, {
filter: (xValue, yValue) => yValue <= 2 || yValue >= 5,
});
expect(result).toStrictEqual({
x: [0, 1, 4, 5, 6, 7, 8, 9, 10],
y: [1, 2, 5, 6, 7, 8, 9, 10, 11],
});
});
});
1 change: 1 addition & 0 deletions src/xy/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ export * from './xyCumulativeDistributionStatistics';
export * from './xyEnsureGrowingX';
export * from './xyEquallySpaced';
export * from './xyExtract';
export * from './xyFilter';
export * from './xyFilterMinYValue';
export * from './xyFilterTopYValues';
export * from './xyFilterX';
Expand Down
33 changes: 33 additions & 0 deletions src/xy/xyFilter.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import { DataXY } from 'cheminfo-types';

export interface XYFilterOptions {
/** callback
* @default ()=>true
*/
filter?: (x: number, y: number) => boolean;
}

/** Filter an array x/y based on various criteria x points are expected to be sorted
*
* @param data - object containing 2 properties x and y
* @param options - options
* @return filtered array
*/
export function xyFilter(data: DataXY, options: XYFilterOptions = {}): DataXY {
const { x, y } = data;
const { filter } = options;
const newX = [];
const newY = [];

for (let i = 0; i < x.length; i++) {
if (!filter || filter(x[i], y[i])) {
newX.push(x[i]);
newY.push(y[i]);
}
}

return {
x: newX,
y: newY,
};
}

0 comments on commit 223f6f3

Please sign in to comment.