Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feat: Add tapOnce and tapOnceOnFirstTruthy Operators #490

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
73 changes: 73 additions & 0 deletions docs/src/content/docs/utilities/Operators/tap-once.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
````markdown
---
title: tapOnce / tapOnceOnFirstTruthy
description: Standalone RxJS operators for executing functions conditionally on emitted values.
entryPoint: ngxtension/tap-once
badge: stable
contributors: ['andreas-dorner']
---

## Import

```typescript
import { tapOnce, tapOnceOnFirstTruthy } from 'ngxtension/tap-once';
```
````

## Usage

### tapOnce

Executes the provided function only once when the value at the specified index is emitted.

```typescript
import { from } from 'rxjs';
import { tapOnce } from 'ngxtension/tap-once';

const in$ = from([1, 2, 3, 4, 5]);
const out$ = in$.pipe(tapOnce((value) => console.log(value), 2));

out$.subscribe(); // logs: 3
```

#### Parameters

- `tapFn`: Function to execute on the value at the specified index.
- `tapIndex`: Index at which to execute the function (default is 0).

### tapOnceOnFirstTruthy

Executes the provided function only once when the first truthy value is emitted.

```typescript
import { from } from 'rxjs';
import { tapOnceOnFirstTruthy } from 'ngxtension/tap-once';

const in$ = from([0, null, false, 3, 4, 5]);
const out$ = in$.pipe(tapOnceOnFirstTruthy((value) => console.log(value)));

out$.subscribe(); // logs: 3
```

#### Parameters

- `tapFn`: Function to execute on the first truthy value.

## API

### tapOnce

- `tapFn: (t: T) => void`
- `tapIndex: number = 0`

### tapOnceOnFirstTruthy

- `tapFn: (t: T) => void`

### Validation

- Throws an error if `tapIndex` is negative.

```

```
3 changes: 3 additions & 0 deletions libs/ngxtension/tapOnce/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
# ngxtension/tap-once

Secondary entry point of `ngxtension`. It can be used by importing from `ngxtension/tap-once`.
5 changes: 5 additions & 0 deletions libs/ngxtension/tapOnce/ng-package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"lib": {
"entryFile": "src/index.ts"
}
}
20 changes: 20 additions & 0 deletions libs/ngxtension/tapOnce/project.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
{
"name": "ngxtension/tap-once",
"$schema": "../../../node_modules/nx/schemas/project-schema.json",
"projectType": "library",
"sourceRoot": "libs/ngxtension/tap-once/src",
"targets": {
"test": {
"executor": "@nx/jest:jest",
"outputs": ["{workspaceRoot}/coverage/{projectRoot}"],
"options": {
"jestConfig": "libs/ngxtension/jest.config.ts",
"testPathPattern": ["tap-once"]
}
},
"lint": {
"executor": "@nx/eslint:lint",
"outputs": ["{options.outputFile}"]
}
}
}
1 change: 1 addition & 0 deletions libs/ngxtension/tapOnce/src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from './tap-once';
76 changes: 76 additions & 0 deletions libs/ngxtension/tapOnce/src/tap-once.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
import { from, toArray } from 'rxjs';
import { tapOnce, tapOnceOnFirstTruthy } from './tap-once';

describe(tapOnce.name, () => {
it('should execute the function only once at the specified index', (done) => {
const tapFn = jest.fn();
const in$ = from([1, 2, 3, 4, 5]);
const out$ = in$.pipe(tapOnce(tapFn, 2));

out$.pipe(toArray()).subscribe((r) => {
expect(r).toEqual([1, 2, 3, 4, 5]);
expect(tapFn).toHaveBeenCalledTimes(1);
expect(tapFn).toHaveBeenCalledWith(3);
done();
});
});

it('should execute the function only once at the default index 0', (done) => {
const tapFn = jest.fn();
const in$ = from([1, 2, 3, 4, 5]);
const out$ = in$.pipe(tapOnce(tapFn));

out$.pipe(toArray()).subscribe((r) => {
expect(r).toEqual([1, 2, 3, 4, 5]);
expect(tapFn).toHaveBeenCalledTimes(1);
expect(tapFn).toHaveBeenCalledWith(1);
done();
});
});

it('should throw an error if tapIndex is negative', () => {
expect(() => tapOnce(() => {}, -1)).toThrow(
'tapIndex must be a non-negative integer',
);
});
});

describe(tapOnceOnFirstTruthy.name, () => {
it('should execute the function only once on the first truthy value', (done) => {
const tapFn = jest.fn();
const in$ = from([0, null, false, 3, 4, 5]);
const out$ = in$.pipe(tapOnceOnFirstTruthy(tapFn));

out$.pipe(toArray()).subscribe((r) => {
expect(r).toEqual([0, null, false, 3, 4, 5]);
expect(tapFn).toHaveBeenCalledTimes(1);
expect(tapFn).toHaveBeenCalledWith(3);
done();
});
});

it('should not execute the function if there are no truthy values', (done) => {
const tapFn = jest.fn();
const in$ = from([0, null, false, undefined]);
const out$ = in$.pipe(tapOnceOnFirstTruthy(tapFn));

out$.pipe(toArray()).subscribe((r) => {
expect(r).toEqual([0, null, false, undefined]);
expect(tapFn).not.toHaveBeenCalled();
done();
});
});

it('should execute the function only once even if there are multiple truthy values', (done) => {
const tapFn = jest.fn();
const in$ = from([1, 2, 3, 4, 5]);
const out$ = in$.pipe(tapOnceOnFirstTruthy(tapFn));

out$.pipe(toArray()).subscribe((r) => {
expect(r).toEqual([1, 2, 3, 4, 5]);
expect(tapFn).toHaveBeenCalledTimes(1);
expect(tapFn).toHaveBeenCalledWith(1);
done();
});
});
});
46 changes: 46 additions & 0 deletions libs/ngxtension/tapOnce/src/tap-once.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
import { MonoTypeOperatorFunction, concatMap, of, type Observable } from 'rxjs';
import { tap } from 'rxjs/operators';

/**
* Executes the provided function only once when the first truthy value is emitted.
* @param tapFn - Function to execute on the first truthy value.
* @returns MonoTypeOperatorFunction
*/
export function tapOnceOnFirstTruthy<T>(
tapFn: (t: T) => void,
): MonoTypeOperatorFunction<T> {
let firstTruthy = true;
return (source$: Observable<T>) =>
source$.pipe(
tap((value) => {
if (firstTruthy && !!value) {
tapFn(value);
firstTruthy = false;
}
}),
);
}

/**
* Executes the provided function only once when the value at the specified index is emitted.
* @param tapFn - Function to execute on the value at the specified index.
* @param tapIndex - Index at which to execute the function (default is 0).
* @returns MonoTypeOperatorFunction
*/
export function tapOnce<T>(
tapFn: (t: T) => void,
tapIndex = 0,
): MonoTypeOperatorFunction<T> {
if (tapIndex < 0) {
throw new Error('tapIndex must be a non-negative integer');
}
return (source$: Observable<T>) =>
source$.pipe(
concatMap((value, index) => {
if (index === tapIndex) {
tapFn(value);
}
return of(value);
}),
);
}