31 lines
915 B
Plaintext
31 lines
915 B
Plaintext
const PATTERN_REGEX = /%(-)?(\d+)?(?:\.(\d+))?([a-zA-Z%])(?:\{([^}]+)\})?/g;
|
|
function compilePattern(pattern, createConverter, literalConverter) {
|
|
const converters = [];
|
|
let lastIndex = 0;
|
|
let match;
|
|
while ((match = PATTERN_REGEX.exec(pattern)) !== null) {
|
|
const [full, align, minWidth, precision, specifier, format] = match;
|
|
if (match.index > lastIndex) {
|
|
converters.push(literalConverter(pattern.substring(lastIndex, match.index)));
|
|
}
|
|
const converter = createConverter(
|
|
specifier,
|
|
align === "-",
|
|
parseInt(minWidth || "0", 10),
|
|
parseInt(precision || "0", 10),
|
|
format
|
|
);
|
|
if (converter) {
|
|
converters.push(converter);
|
|
}
|
|
lastIndex = match.index + full.length;
|
|
}
|
|
if (lastIndex < pattern.length) {
|
|
converters.push(literalConverter(pattern.substring(lastIndex)));
|
|
}
|
|
return converters;
|
|
}
|
|
export {
|
|
compilePattern as default
|
|
};
|