Skip to content

Instantly share code, notes, and snippets.

@CodeByKwakes
Last active March 16, 2023 12:01
Show Gist options
  • Save CodeByKwakes/57a5803039925902146097954fe56190 to your computer and use it in GitHub Desktop.
Save CodeByKwakes/57a5803039925902146097954fe56190 to your computer and use it in GitHub Desktop.
Pipe Examples #angular
@Input() formDataObj;
pageProps = [];
private oldFormSetup() {
const formDataObj = {};
for (const propName of Object.keys(this.formDataObj)) {
console.log('prop name', propName);
formDataObj[propName] = new FormControl(this.formDataObj[propName]);
console.log('value', formDataObj[propName].value);
this.pageProps.push({
key: propName,
label: propName,
value: formDataObj[propName].value,
type: this.typeOf(formDataObj[propName].value)
});
console.log('pageProps', this.pageProps);
console.log('formData', formDataObj);
}
this.form = new FormGroup(formDataObj);
}
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'filter'
})
export class FilterPipe implements PipeTransform {
transform(items: any[], searchText: string): any[] {
if (!items) return [];
if (!searchText) return items;
searchText = searchText.toLowerCase();
return items.filter((item) => {
return item.toLowerCase().includes(searchText);
});
}
}
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'filter'
})
export class FilterPipe implements PipeTransform {
transform(items: any[], searchText: string): any[] {
if (!items || !searchText) {
return items;
}
const lowerSearch = searchText.toLowerCase();
return items.filter((item) => item.toLowerCase().includes(lowerSearch));
}
}
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'key'
})
export class KeyPipe implements PipeTransform {
public transform(value: any, args?: any): any {
return Object.keys(value);
}
}

You

 

Optimize the following code

ChatGPT

To optimize the given code, we can follow these approaches:

Approach 1:

As the KeyPipe is a pure pipe that means it won't change the output if the input remains the same. So, we can set its pure property to true explicitly to achieve better performance. Setting pure to true notifies Angular that the Pipe is not having any side effects on the input and hence no need to rerun on every change detection cycle.

Approach 2:

The current KeyPipe implementation will call Object.keys() method on every input value, even for the same input value over time, which can be avoided by caching the result for each unique input value. We can use memoization technique to cache the previous results of Object.keys() method.

Here's how we can apply these approaches:

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'key',
  pure: true // approach 1
})
export class KeyPipe implements PipeTransform {

  private readonly cache = new Map<any, any>(); // approach 2

  public transform(value: any, args?: any): any {
    if (this.cache.has(value)) { // approach 2
      return this.cache.get(value);
    }
    
    const keys = Object.keys(value);
    this.cache.set(value, keys); // approach 2
    return keys;
  }

}

In Approach 2, we are creating a private instance variable named cache with type Map<any, any> in which we store the previous results of Object.keys(value) method so that we don't have to recalculate Object.keys(value) for an already seen value again.

Instead, for each new input, we first check whether we have cached the result previously or not by calling cache.has(value). If yes, we retrieve the cached result using cache.get(value).

If not previously cached, then we calculate the keys using Object.keys(value) and save them in the cache using this.cache.set(). At last, we return the array of keys.

These approaches will improve the performance of KeyPipe in Angular applications where it's used.

import { Pipe, PipeTransform } from '@angular/core';
import {DomSanitizer} from "@angular/platform-browser";
/**
* Generated class for the SafeHtmlPipe pipe.
*
* See https://angular.io/api/core/Pipe for more info on Angular Pipes.
*/
@Pipe({
name: 'safeHtml',
})
export class SafeHtmlPipe implements PipeTransform {
constructor(private sanitizer:DomSanitizer){}
transform(html) {
return this.sanitizer.bypassSecurityTrustHtml(html);
}
}
import { Pipe, PipeTransform } from '@angular/core';
import {
DomSanitizer,
SafeHtml,
SafeStyle,
SafeScript,
SafeUrl,
SafeResourceUrl
} from '@angular/platform-browser';
@Pipe({
name: 'safe'
})
export class SafePipe implements PipeTransform {
constructor(protected sanitizer: DomSanitizer) {}
public transform(
value: any,
type: string
): SafeHtml | SafeStyle | SafeScript | SafeUrl | SafeResourceUrl {
switch (type) {
case 'html':
return this.sanitizer.bypassSecurityTrustHtml(value);
case 'style':
return this.sanitizer.bypassSecurityTrustStyle(value);
case 'script':
return this.sanitizer.bypassSecurityTrustScript(value);
case 'url':
return this.sanitizer.bypassSecurityTrustUrl(value);
case 'resourceUrl':
return this.sanitizer.bypassSecurityTrustResourceUrl(value);
default:
throw new Error(`Invalid safe type specified: ${type}`);
}
}
}
import { Pipe, PipeTransform } from '@angular/core';
import {
DomSanitizer,
SafeHtml,
SafeStyle,
SafeScript,
SafeUrl,
SafeResourceUrl
} from '@angular/platform-browser';
interface SafeTypeMap {
[key: string]: keyof DomSanitizer;
}
const safeTypeMap: SafeTypeMap = {
html: 'bypassSecurityTrustHtml',
style: 'bypassSecurityTrustStyle',
script: 'bypassSecurityTrustScript',
url: 'bypassSecurityTrustUrl',
resourceUrl: 'bypassSecurityTrustResourceUrl'
};
@Pipe({
name: 'safe'
})
export class SafePipe implements PipeTransform {
constructor(private sanitizer: DomSanitizer) {}
public transform(
value: any,
type: string
): SafeHtml | SafeStyle | SafeScript | SafeUrl | SafeResourceUrl {
const functionName = safeTypeMap[type];
if (functionName) {
return this.sanitizer[functionName](value);
}
// If the type is not found, return the original unsafe value
return value;
}
}
import { Injectable, Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'searchfilter'
})
@Injectable()
export class SearchFilterPipe implements PipeTransform {
transform(items: any[], field: string, value: string): any[] {
if (!items) return [];
return items.filter((it) => it[field] == value);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment