MCPcopy Create free account
hub / github.com/SlexAxton/listpattern / listPatternFormatter

Function listPatternFormatter

index.js:44–104  ·  view source on GitHub ↗
(list, _config)

Source from the content-addressed store, hash-verified

42}
43
44function listPatternFormatter(list, _config) {
45 // Use the default config patternType by default…
46 var patternTypeResolution = this.__config__.patternType;
47
48 // If we're overriding the pattern type just for this format call, do it
49 if (_config && _config.patternType) {
50 patternTypeResolution = _config.patternType;
51 }
52
53 var listPatternRules =
54 this.__cldr__[LIST_PATTERN_PREFIX + patternTypeResolution] ||
55 this.__cldr__[LIST_PATTERN_PREFIX + this.__config__.patternType] ||
56 this.__cldr__[LIST_PATTERN_PREFIX + DEFAULT_LIST_PATTERN];
57
58 if (!listPatternRules) {
59 throw new Error('Unable to find a valid list pattern or fallback pattern.');
60 }
61
62 // Check for literal length rules
63 if (listPatternRules.hasOwnProperty(list.length + '')) {
64 return formatLiteralPattern(list, listPatternRules[list.length + '']);
65 }
66
67 // If we're here, we've got a standard "start" "middle" "end" situation
68 var result = '';
69
70 // This is the "correct" output, but if someone got here, they probably
71 // already wanted to handle the empty case.
72 if (list.length < 1) {
73 return '';
74 }
75
76 // This is also a 'silent failure' mode, but ideally handled externally
77 if (list.length === 1) {
78 return list[0];
79 }
80
81 // Start with end
82 var pointer = list.length - 1;
83 result = listPatternRules.end
84 .replace('{1}', list[pointer])
85 .replace('{0}', list[pointer - 1]);
86
87 // We used up 2 indexes already
88 pointer = pointer - 2;
89
90 // Fill in the middle section
91 while (pointer > 0) {
92 result = listPatternRules.middle
93 .replace('{1}', result)
94 .replace('{0}', list[pointer]);
95 pointer -= 1;
96 }
97
98 // Handle the 'start' base-case
99 result = listPatternRules.start
100 .replace('{1}', result)
101 .replace('{0}', list[pointer]);

Callers

nothing calls this directly

Calls 1

formatLiteralPatternFunction · 0.85

Tested by

no test coverage detected