-
Notifications
You must be signed in to change notification settings - Fork 36
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Support type-based transformers #43
Comments
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. :) Option 1: Transformersconst fmt = format.create({
string: str => "'" + str + "'",
number: num => num.toLocaleString(),
});
fmt("Welcome back, {!string}! You have {!number} unread messages.", "Alice", 1000); Option 2: Preprocessing via monomorphic functions// 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)); Option 3: Preprocessing via polymorphic function// 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. :) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
It'd be somewhat helpful to be able to automatically apply transformers based on the
typeof
for a value. For example:The text was updated successfully, but these errors were encountered: