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(call-apply): Implemented call apply Pipes #53

Merged
merged 6 commits into from
Sep 15, 2023
Merged
Show file tree
Hide file tree
Changes from 3 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
10 changes: 9 additions & 1 deletion CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,15 @@ We will review your PR as soon as possible, and your contribution will be greatl
Most likely, you'll need to create new secondary entry point to put the new utility in. To create entry point, use the following command:

```shell
pnx nx g local-plugin:entry-point <name-of-your-utility> --library=ngxtension --skip-module
pnpm exec nx g local-plugin:entry-point <name-of-your-utility> --library=ngxtension --skip-module
```

#### Please write some Tests

Try to cover your new contrib with some tests and make it pass running:

```shell
pnpm exec nx run ngxtension/<name-of-your-utility>:test
```

## Development Setup
Expand Down
1 change: 1 addition & 0 deletions docs/astro.config.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@ export default defineConfig({
{ label: 'resize', link: '/utilities/resize' },
{ label: 'createEffect', link: '/utilities/create-effect' },
{ label: 'ifValidator', link: '/utilities/if-validator' },
{ label: 'call apply Pipes', link: '/utilities/call-apply' },
],
},
],
Expand Down
48 changes: 48 additions & 0 deletions docs/src/content/docs/utilities/call-apply.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
---
title: call apply Pipes
description: ngxtension/call-apply
---

`callPipe` and `applyPipe` are simple standalone pipes that simplify the calling of PURE functions passing params to it; they take advantage of the "memoization" offered by pure pipes in Angular, and ensure that you use them only with PURE functions (aka if you use this inside the body function they throw errors!)

```ts
import { CallPipe, ApplyPipe } from 'ngxtension/if-validation';
```

## Usage

Both `CallPipe` and `ApplyPipe` need a PURE function or method to invoke (aka you can't use `this` in the function body), the difference between the two is only in that invocation order and that `|call` is suitable only for function with 1-param, instead `|apply` works for function with any number of params.

```ts
import { Component, ChangeDetectionStrategy } from '@angular/core';
import { CallPipe, ApplyPipe } from 'ngxtension/call-apply';

@Component({
selector: 'my-app',
standalone: true,
imports: [CallPipe, ApplyPipe],
template: `
<button (click)="updateClock()">UPDATE CLOCK</button>

<b>call UTC: {{ now | call : ISOFormat }}</b>
<i>with apply: {{ ISOFormat | apply : now }}</i>
<p>{{ join | apply : 'Hello' : 'world' : '!' }}</p>

<!-- IF YOU UNCOMMENT NEXT LINE IT WILL THROW ERROR
<h1>THIS IS NOT PURE: {{ updateClock | apply }}</h1>
-->
`,
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class App {
public now = new Date(42, 42, 42, 42, 42, 42, 42); //"1945-08-12T16:42:42.042Z"
public ISOFormat = (date: Date) => date.toISOString();
public join(...rest: string[]) {
return rest.join(' ');
}
public updateClock() {
this.now = new Date();
return this.now;
}
}
```
3 changes: 3 additions & 0 deletions libs/ngxtension/call-apply/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
# ngxtension/call-apply

Secondary entry point of `ngxtension`. It can be used by importing from `ngxtension/call-apply`.
5 changes: 5 additions & 0 deletions libs/ngxtension/call-apply/ng-package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"lib": {
"entryFile": "src/index.ts"
}
}
33 changes: 33 additions & 0 deletions libs/ngxtension/call-apply/project.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
{
"name": "ngxtension/call-apply",
"$schema": "../../../node_modules/nx/schemas/project-schema.json",
"projectType": "library",
"sourceRoot": "libs/ngxtension/call-apply/src",
"targets": {
"test": {
"executor": "@nx/jest:jest",
"outputs": ["{workspaceRoot}/coverage/{projectRoot}"],
"options": {
"jestConfig": "libs/ngxtension/jest.config.ts",
"testPathPattern": ["call-apply"],
"passWithNoTests": true
},
"configurations": {
"ci": {
"ci": true,
"codeCoverage": true
}
}
},
"lint": {
"executor": "@nx/linter:eslint",
"outputs": ["{options.outputFile}"],
"options": {
"lintFilePatterns": [
"libs/ngxtension/call-apply/**/*.ts",
"libs/ngxtension/call-apply/**/*.html"
]
}
}
}
}
137 changes: 137 additions & 0 deletions libs/ngxtension/call-apply/src/call-apply.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,137 @@
import { Component } from '@angular/core';
import { TestBed } from '@angular/core/testing';
import { By } from '@angular/platform-browser';
import { ApplyPipe, CallPipe } from './call-apply';

describe(CallPipe.name, () => {
@Component({
standalone: true,
template: `
<p>{{ now | call : ISOFormat }}</p>
<b>{{ now | call : doSomething }}</b>
`,
imports: [CallPipe],
})
class Dummy {
now = new Date(42, 42, 42, 42, 42, 42, 42);
ISOFormat(d: Date) {
return d.toISOString();
}
doSomething() {
return 42;
}
}

@Component({
standalone: true,
template: `
{{ 'WILL FAIL' | call : notPureFn }}
`,
imports: [CallPipe],
})
class FailDummy {
now = new Date(42, 42, 42, 42, 42, 42, 42);
notPureFn() {
this.now = new Date();
return this.now.toISOString();
}
}

it('can call PURE function with a param', () => {
const fixture = TestBed.createComponent(Dummy);
fixture.detectChanges();

const elP = fixture.debugElement.query(By.css('p'));
expect(elP.nativeElement.textContent).toContain('1945-08-12T16:42:42.042Z');
});
it('can call PURE function without params', () => {
const fixture = TestBed.createComponent(Dummy);
fixture.detectChanges();

const elB = fixture.debugElement.query(By.css('b'));
expect(elB.nativeElement.textContent).toContain('42');
});
it('will fail if the function is NOT PURE (using this in the body)', () => {
expect(() => {
const fixture = TestBed.createComponent(FailDummy);
fixture.detectChanges();
}).toThrowError(
`DON'T USE this INSIDE A FUNCTION CALLED BY | call OR | apply IT MUST BE A PURE FUNCTION!`
);
});
});

describe(ApplyPipe.name, () => {
@Component({
standalone: true,
template: `
<i>{{ IamPure | apply }}</i>
<p>{{ ISOFormat | apply : now }}</p>
<b>{{ doSomething | apply : 'Hello world' }}</b>
<a>{{ doSomething | apply : 'Prova' : 1 : 2 : 3 }}</a>
`,
imports: [ApplyPipe],
})
class Dummy {
now = new Date(42, 42, 42, 42, 42, 42, 42);
IamPure = () => 42;
ISOFormat(d: Date) {
return d.toISOString();
}
doSomething(a: string, ...rest: number[]) {
return rest.reduce((a, b) => a + b, a);
}
}

@Component({
standalone: true,
template: `
{{ notPureFn | apply }}
`,
imports: [ApplyPipe],
})
class FailDummy {
now = new Date(42, 42, 42, 42, 42, 42, 42);
notPureFn() {
this.now = new Date();
return this.now.toISOString();
}
}

it('can apply PURE function without params', () => {
const fixture = TestBed.createComponent(Dummy);
fixture.detectChanges();

const elI = fixture.debugElement.query(By.css('i'));
expect(elI.nativeElement.textContent).toContain('42');
});
it('can apply PURE function with a param', () => {
const fixture = TestBed.createComponent(Dummy);
fixture.detectChanges();

const elP = fixture.debugElement.query(By.css('p'));
expect(elP.nativeElement.textContent).toContain('1945-08-12T16:42:42.042Z');
});
it('can apply PURE function with lesser param', () => {
const fixture = TestBed.createComponent(Dummy);
fixture.detectChanges();

const elB = fixture.debugElement.query(By.css('b'));
expect(elB.nativeElement.textContent).toContain('Hello world');
});
it('can apply PURE function with more rest param', () => {
const fixture = TestBed.createComponent(Dummy);
fixture.detectChanges();

const elA = fixture.debugElement.query(By.css('a'));
expect(elA.nativeElement.textContent).toContain('Prova123');
});
it('will fail if the function is NOT PURE (using this in the body)', () => {
expect(() => {
const fixture = TestBed.createComponent(FailDummy);
fixture.detectChanges();
}).toThrowError(
`DON'T USE this INSIDE A FUNCTION CALLED BY | call OR | apply IT MUST BE A PURE FUNCTION!`
);
});
});
47 changes: 47 additions & 0 deletions libs/ngxtension/call-apply/src/call-apply.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
import { Pipe, PipeTransform } from '@angular/core';

const error_this = function () {
throw new Error(
`DON'T USE this INSIDE A FUNCTION CALLED BY | call OR | apply IT MUST BE A PURE FUNCTION!`
);
};
const NOTHIS = !('Proxy' in window)
? Object.seal({})
: new Proxy(
{},
{
get: error_this,
set: error_this,
deleteProperty: error_this,
has: error_this,
}
);

@Pipe({
name: 'call',
pure: true,
standalone: true,
})
export class CallPipe implements PipeTransform {
transform<T = any, R = any>(value: T, args?: (param?: T) => R): R {
nartc marked this conversation as resolved.
Show resolved Hide resolved
if (typeof args !== 'function')
throw new TypeError('You must pass a PURE funciton to | call');
return args?.call(NOTHIS, value);
}
}

@Pipe({
name: 'apply',
pure: true,
standalone: true,
})
export class ApplyPipe implements PipeTransform {
transform<TFunction extends (...args: any[]) => any>(
fn: TFunction,
...args: Parameters<TFunction>
): ReturnType<TFunction> {
if (typeof fn !== 'function')
throw new TypeError('You must use | apply on a PURE function');
return fn.apply(NOTHIS, args);
}
}
1 change: 1 addition & 0 deletions libs/ngxtension/call-apply/src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from './call-apply';
3 changes: 2 additions & 1 deletion tsconfig.base.json
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
"ngxtension/assert-injector": [
"libs/ngxtension/assert-injector/src/index.ts"
],
"ngxtension/call-apply": ["libs/ngxtension/call-apply/src/index.ts"],
"ngxtension/computed-from": [
"libs/ngxtension/computed-from/src/index.ts"
],
Expand All @@ -30,12 +31,12 @@
"ngxtension/create-injection-token": [
"libs/ngxtension/create-injection-token/src/index.ts"
],
"ngxtension/if-validator": ["libs/ngxtension/if-validator/src/index.ts"],
"ngxtension/inject-destroy": [
"libs/ngxtension/inject-destroy/src/index.ts"
],
"ngxtension/repeat": ["libs/ngxtension/repeat/src/index.ts"],
"ngxtension/resize": ["libs/ngxtension/resize/src/index.ts"],
"ngxtension/if-validator": ["libs/ngxtension/if-validator/src/index.ts"],
"plugin": ["libs/plugin/src/index.ts"]
}
},
Expand Down