2016-04-28 17:50:03 -07:00
|
|
|
import {Injectable, PipeTransform, Pipe} from '@angular/core';
|
2016-05-01 22:50:37 -07:00
|
|
|
import {isStringMap, StringWrapper, isPresent, RegExpWrapper} from '../../src/facade/lang';
|
2016-02-26 10:02:52 -08:00
|
|
|
import {InvalidPipeArgumentException} from './invalid_pipe_argument_exception';
|
|
|
|
|
|
|
|
var interpolationExp: RegExp = RegExpWrapper.create('#');
|
|
|
|
|
|
|
|
/**
|
|
|
|
*
|
|
|
|
* Maps a value to a string that pluralizes the value properly.
|
|
|
|
*
|
|
|
|
* ## Usage
|
|
|
|
*
|
|
|
|
* expression | i18nPlural:mapping
|
|
|
|
*
|
|
|
|
* where `expression` is a number and `mapping` is an object that indicates the proper text for
|
|
|
|
* when the `expression` evaluates to 0, 1, or some other number. You can interpolate the actual
|
|
|
|
* value into the text using the `#` sign.
|
|
|
|
*
|
|
|
|
* ## Example
|
|
|
|
*
|
|
|
|
* ```
|
|
|
|
* <div>
|
|
|
|
* {{ messages.length | i18nPlural: messageMapping }}
|
|
|
|
* </div>
|
|
|
|
*
|
|
|
|
* class MyApp {
|
|
|
|
* messages: any[];
|
|
|
|
* messageMapping: any = {
|
|
|
|
* '=0': 'No messages.',
|
|
|
|
* '=1': 'One message.',
|
|
|
|
* 'other': '# messages.'
|
|
|
|
* }
|
|
|
|
* ...
|
|
|
|
* }
|
|
|
|
* ```
|
|
|
|
*
|
|
|
|
*/
|
|
|
|
@Pipe({name: 'i18nPlural', pure: true})
|
|
|
|
@Injectable()
|
|
|
|
export class I18nPluralPipe implements PipeTransform {
|
2016-04-22 15:33:32 -07:00
|
|
|
transform(value: number, pluralMap: {[count: string]: string}): string {
|
2016-02-26 10:02:52 -08:00
|
|
|
var key: string;
|
|
|
|
var valueStr: string;
|
|
|
|
|
|
|
|
if (!isStringMap(pluralMap)) {
|
|
|
|
throw new InvalidPipeArgumentException(I18nPluralPipe, pluralMap);
|
|
|
|
}
|
|
|
|
|
|
|
|
key = value === 0 || value === 1 ? `=${value}` : 'other';
|
|
|
|
valueStr = isPresent(value) ? value.toString() : '';
|
|
|
|
|
|
|
|
return StringWrapper.replaceAll(pluralMap[key], interpolationExp, valueStr);
|
|
|
|
}
|
|
|
|
}
|