angular-cn/packages/common/src/pipes/i18n_plural_pipe.ts

48 lines
1.4 KiB
TypeScript
Raw Normal View History

/**
* @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
*/
import {Pipe, PipeTransform} from '@angular/core';
import {NgLocalization, getPluralCategory} from '../localization';
import {invalidPipeArgumentError} from './invalid_pipe_argument_error';
2016-06-17 10:57:50 -07:00
const _INTERPOLATION_REGEXP: RegExp = /#/g;
/**
* @ngModule CommonModule
* @whatItDoes Maps a value to a string that pluralizes the value according to locale rules.
* @howToUse `expression | i18nPlural:mapping`
* @description
*
* Where:
* - `expression` is a number.
* - `mapping` is an object that mimics the ICU format, see
* http://userguide.icu-project.org/formatparse/messages
*
* ## Example
*
* {@example common/pipes/ts/i18n_pipe.ts region='I18nPluralPipeComponent'}
*
* @experimental
*/
@Pipe({name: 'i18nPlural', pure: true})
export class I18nPluralPipe implements PipeTransform {
constructor(private _localization: NgLocalization) {}
transform(value: number, pluralMap: {[count: string]: string}): string {
if (value == null) return '';
2016-10-19 13:42:39 -07:00
if (typeof pluralMap !== 'object' || pluralMap === null) {
throw invalidPipeArgumentError(I18nPluralPipe, pluralMap);
}
const key = getPluralCategory(value, Object.keys(pluralMap), this._localization);
2016-09-11 00:27:56 -07:00
return pluralMap[key].replace(_INTERPOLATION_REGEXP, value.toString());
}
}