2016-06-23 09:47:54 -07:00
|
|
|
/**
|
|
|
|
* @license
|
|
|
|
* Copyright Google Inc. All Rights Reserved.
|
|
|
|
*
|
|
|
|
* Use of this source code is governed by an MIT-style license that can be
|
|
|
|
* found in the LICENSE file at https://angular.io/license
|
|
|
|
*/
|
|
|
|
|
2016-06-08 16:38:52 -07:00
|
|
|
import {Pipe, PipeTransform} from '@angular/core';
|
2016-06-23 11:44:05 -07:00
|
|
|
import {NgLocalization, getPluralCategory} from '../localization';
|
2016-08-25 00:50:16 -07:00
|
|
|
import {InvalidPipeArgumentError} from './invalid_pipe_argument_error';
|
2016-02-26 10:02:52 -08:00
|
|
|
|
2016-06-17 10:57:50 -07:00
|
|
|
const _INTERPOLATION_REGEXP: RegExp = /#/g;
|
2016-02-26 10:02:52 -08:00
|
|
|
|
|
|
|
/**
|
2016-09-08 21:41:09 -07:00
|
|
|
* @ngModule CommonModule
|
|
|
|
* @whatItDoes Maps a value to a string that pluralizes the value according to locale rules.
|
|
|
|
* @howToUse `expression | i18nPlural:mapping`
|
|
|
|
* @description
|
2016-02-26 10:02:52 -08:00
|
|
|
*
|
2016-09-08 21:41:09 -07:00
|
|
|
* Where:
|
|
|
|
* - `expression` is a number.
|
|
|
|
* - `mapping` is an object that mimics the ICU format, see
|
|
|
|
* http://userguide.icu-project.org/formatparse/messages
|
2016-02-26 10:02:52 -08:00
|
|
|
*
|
|
|
|
* ## Example
|
|
|
|
*
|
2016-09-08 21:41:09 -07:00
|
|
|
* {@example common/pipes/ts/i18n_pipe.ts region='I18nPluralPipeComponent'}
|
2016-02-26 10:02:52 -08:00
|
|
|
*
|
2016-05-27 11:24:05 -07:00
|
|
|
* @experimental
|
2016-02-26 10:02:52 -08:00
|
|
|
*/
|
|
|
|
@Pipe({name: 'i18nPlural', pure: true})
|
|
|
|
export class I18nPluralPipe implements PipeTransform {
|
2016-06-23 11:44:05 -07:00
|
|
|
constructor(private _localization: NgLocalization) {}
|
|
|
|
|
2016-04-22 15:33:32 -07:00
|
|
|
transform(value: number, pluralMap: {[count: string]: string}): string {
|
2017-01-10 14:45:11 +01:00
|
|
|
if (value == null) return '';
|
2016-02-26 10:02:52 -08:00
|
|
|
|
2016-10-19 13:42:39 -07:00
|
|
|
if (typeof pluralMap !== 'object' || pluralMap === null) {
|
2016-08-25 00:50:16 -07:00
|
|
|
throw new InvalidPipeArgumentError(I18nPluralPipe, pluralMap);
|
2016-02-26 10:02:52 -08:00
|
|
|
}
|
|
|
|
|
2016-08-04 19:35:41 +02:00
|
|
|
const key = getPluralCategory(value, Object.keys(pluralMap), this._localization);
|
2016-02-26 10:02:52 -08:00
|
|
|
|
2016-09-11 00:27:56 -07:00
|
|
|
return pluralMap[key].replace(_INTERPOLATION_REGEXP, value.toString());
|
2016-02-26 10:02:52 -08:00
|
|
|
}
|
|
|
|
}
|