Browse Source

fix count escape (#17841)

pull/17888/head
zombieJ 5 years ago
committed by GitHub
parent
commit
bce3696ec0
No known key found for this signature in database GPG Key ID: 4AEE18F83AFDEB23
  1. 7
      components/statistic/__tests__/index.test.js
  2. 17
      components/statistic/utils.tsx

7
components/statistic/__tests__/index.test.js

@ -3,6 +3,7 @@ import MockDate from 'mockdate';
import moment from 'moment';
import { mount } from 'enzyme';
import Statistic from '..';
import { formatTimeStr } from '../utils';
const delay = timeout => new Promise(resolve => setTimeout(resolve, timeout));
@ -104,4 +105,10 @@ describe('Statistic', () => {
});
});
});
describe('utils', () => {
it('format should support escape', () => {
expect(formatTimeStr(1000 * 60 * 60 * 24, 'D [Day]')).toBe('1 Day');
});
});
});

17
components/statistic/utils.tsx

@ -35,10 +35,14 @@ const timeUnits: [string, number][] = [
['S', 1], // million seconds
];
function formatTimeStr(duration: number, format: string) {
export function formatTimeStr(duration: number, format: string) {
let leftDuration: number = duration;
return timeUnits.reduce((current, [name, unit]) => {
const escapeRegex = /\[[^\]]*\]/g;
const keepList: string[] = (format.match(escapeRegex) || []).map(str => str.slice(1, -1));
const templateText = format.replace(escapeRegex, '[]');
const replacedText = timeUnits.reduce((current, [name, unit]) => {
if (current.indexOf(name) !== -1) {
const value = Math.floor(leftDuration / unit);
leftDuration -= value * unit;
@ -48,7 +52,14 @@ function formatTimeStr(duration: number, format: string) {
});
}
return current;
}, format);
}, templateText);
let index = 0;
return replacedText.replace(escapeRegex, () => {
const match = keepList[index];
index += 1;
return match;
});
}
export function formatCountdown(value: countdownValueType, config: CountdownFormatConfig) {

Loading…
Cancel
Save