Skip to content

Instantly share code, notes, and snippets.

@zimejin
Created May 20, 2019 08:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zimejin/61efb0188b428ec46de0451f1015e8a3 to your computer and use it in GitHub Desktop.
Save zimejin/61efb0188b428ec46de0451f1015e8a3 to your computer and use it in GitHub Desktop.
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({ name: 'excerpt' })
export class ExcerptPipe implements PipeTransform {
transform(text: string, limit: number = 5) {
if (text.length <= limit) {
return text;
}
return text.substring(0, limit) + '...';
}
}
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'getValueByKey',
pure: false
})
export class GetValueByKeyPipe implements PipeTransform {
transform(value: any[], id: number, property: string): any {
const filteredObj = value.find(item => {
if (item.id !== undefined) {
return item.id === id;
}
return false;
});
if (filteredObj) {
return filteredObj[property];
}
}
}
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({ name: 'relativeTime' })
export class RelativeTimePipe implements PipeTransform {
transform(value: Date) {
if (!(value instanceof Date)) {
value = new Date(value);
}
const seconds: number = Math.floor(((new Date()).getTime() - value.getTime()) / 1000);
let interval: number = Math.floor(seconds / 31536000);
if (interval > 1) {
return interval + ' years ago';
}
interval = Math.floor(seconds / 2592000);
if (interval > 1) {
return interval + ' months ago';
}
interval = Math.floor(seconds / 86400);
if (interval > 1) {
return interval + ' days ago';
}
interval = Math.floor(seconds / 3600);
if (interval > 1) {
return interval + ' hours ago';
}
interval = Math.floor(seconds / 60);
if (interval > 1) {
return interval + ' minutes ago';
}
return Math.floor(seconds) + ' seconds ago';
}
}
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { ExcerptPipe } from './excerpt.pipe';
import { GetValueByKeyPipe } from './get-value-by-key.pipe';
import { RelativeTimePipe } from './relative-time.pipe';
const pipes = [
ExcerptPipe,
GetValueByKeyPipe,
RelativeTimePipe
];
@NgModule({
imports: [
CommonModule
],
declarations: pipes,
exports: pipes
})
export class SharedPipesModule { }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment