Created
December 14, 2018 15:10
-
-
Save oleersoy/e2a9fde0383ec5e2ece0a201374e5dcf to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Pipe, PipeTransform } from '@angular/core'; | |
/** | |
* Turns the array into a sentence. | |
* | |
* @example | |
* {{ ['Stephen', 'Trevor' ] | AddCommas:'Customer' }} | |
*/ | |
@Pipe({ name: 'AddCommas' }) | |
export class AddCommasPipe implements PipeTransform { | |
transform(arr: null | string[], noun: string) { | |
const UNKNOWN = `${noun} Unknown`; | |
if (!arr) { | |
return UNKNOWN; | |
} | |
switch (arr.length) { | |
case 0: | |
return UNKNOWN; | |
case 1: | |
return arr[0]; | |
case 2: | |
return arr.join(' and '); | |
default: | |
const last = arr[arr.length - 1]; | |
const remaining = arr.slice(0, -1); | |
return `${remaining.join(', ')}, and ${last}`; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment