Open haykam821 opened 5 years ago
I can think of three ways to achieve the desired result with the existing API. Hopefully you find at least one of these options satisfactory. :)
const fmt = format.create({
string: str => "'" + str + "'",
number: num => num.toLocaleString(),
});
fmt("Welcome back, {!string}! You have {!number} unread messages.", "Alice", 1000);
// string :: String -> String
const string = str => "'" + str + "'";
// number :: Number -> String
const number = num => num.toLocaleString();
format("Welcome back, {}! You have {} unread messages.", string("Alice"), number(1000));
// toString :: Any -> String
const toString = x => {
switch (typeof x) {
case "number": return x.toLocaleString();
case "string": return "'" + x + "'";
default: throw new Error ("Not implemented");
}
};
format("Welcome back, {}! You have {} unread messages.", toString("Alice"), toString(1000));
I suppose this (along with #16, but code for that is not included) could be fixed with a wrapper function:
const typeTransformers = {
string: str => str.toUpperCase(),
number: num => num.toLocaleString(),
};
function coolFormat(str, ...stuff) {
return format(str, ...stuff.map(thing => {
const transform = typeTransformers[typeof thing];
if (typeof transform === "function") {
return transform(thing);
} else {
return thing;
}
});
}
Good idea, @haykam821. :)
It'd be somewhat helpful to be able to automatically apply transformers based on the
typeof
for a value. For example: