This repository has been archived by the owner on Apr 16, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlist.js
111 lines (92 loc) · 2.39 KB
/
list.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
import { BaseFormat} from './base';
import { deconstructPattern } from '../utils';
export function constructParts(pattern, list) {
if (list.length === 1) {
return [{type: 'element', value: list[0]}];
}
const elem0 = typeof list[0] === 'string' ?
{type: 'element', value: list[0]} : list[0];
let elem1;
if (list.length === 2) {
if (typeof list[1] === 'string') {
elem1 = {type: 'element', value: list[1]};
} else {
elem1 = list[1];
}
} else {
elem1 = constructParts(pattern, list.slice(1));
}
return deconstructPattern(pattern, {
'0': elem0,
'1': elem1
});
}
function FormatToParts(type, style, list) {
if (!Array.isArray(list)) {
return Promise.resolve([
{type: 'element', value: list}
]);
}
const length = list.length;
if (length === 0) {
return Promise.resolve([
{type: 'element', value: ''}
]);
}
if (length === 1) {
return Promise.resolve([
{type: 'element', value: list[0]}
]);
}
if (type === 'unit' || type === 'number') {
return document.l10n.formatValue(`listformat-${type}`).then(pattern => {
return constructParts(pattern, list);
});
}
const strid = `listformat-${type}-${style}`;
if (length === 2) {
return document.l10n.formatValue(`${strid}-2`).then(pattern => {
return constructParts(pattern, list);
});
}
return document.l10n.formatValues(
`${strid}-start`,
`${strid}-middle`,
`${strid}-end`).then(([start, middle, end]) => {
let parts = list[length - 1];
for (let i = length - 2; i >= 0; i--) {
let template = middle;
if (i === length - 2) {
template = end;
} else if (i === 0) {
template = start;
}
parts = constructParts(template, [
list[i],
parts
]);
}
return parts;
}
);
}
export class ListFormat extends BaseFormat {
constructor(locales, options) {
super(locales, options, {
type: 'regular',
style: 'long'
});
}
format(list) {
const type = this['[[Type]]'];
const style = this['[[Style]]'];
return FormatToParts(type, style, list).then(parts => {
return parts.reduce((string, part) => string + part.value, '');
});
}
formatToParts(list) {
const type = this['[[Type]]'];
const style = this['[[Style]]'];
return FormatToParts(type, style, list);
}
}