Skip to content

Instantly share code, notes, and snippets.

@oleersoy
Created December 14, 2018 15:10
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 oleersoy/e2a9fde0383ec5e2ece0a201374e5dcf to your computer and use it in GitHub Desktop.
Save oleersoy/e2a9fde0383ec5e2ece0a201374e5dcf to your computer and use it in GitHub Desktop.
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