Skip to content
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

applying transformer on all placeholders #16

Open
steinerkelvin opened this issue May 9, 2016 · 4 comments
Open

applying transformer on all placeholders #16

steinerkelvin opened this issue May 9, 2016 · 4 comments

Comments

@steinerkelvin
Copy link

Is there a way to apply a transformer to all arguments? I need this because the template string is user provided so I need a way to treat the replacements without forcing the user to write the transformer's name for each placeholder.

@davidchambers
Copy link
Owner

The library doesn't provide this functionality, but you may be able to attain it with a wrapper:

const format = require('string-format');

const transformers = {
  upper: s => s.toUpperCase(),
};

const formatWith = (f, args) => format('{} {} {}', ...args.map(f));

const formatWithByName = (name, args) => formatWith(transformers[name], args);

formatWith(transformers.upper, ['foo', 'bar', 'baz']);
// => "FOO BAR BAZ"
formatWithByName('upper', ['foo', 'bar', 'baz']);
// => "FOO BAR BAZ"

I'm not sure exactly what you have in mind, though, so this may or may not be useful. :)

@steinerkelvin
Copy link
Author

steinerkelvin commented May 11, 2016

Nice approach, but it think it won't be useful in my case. It's because the argument is actually a nested Object and dot notation will be used in the template string.

I've already got a way to process each value inside the object, so my problem is with unexpected property names. If the user try to access a property that doesn't exists string-format will just return an empty string:

format = require("string-format");

data = {
  a: {name: "A name"}
}

format("a.name: '{a.name}'", data); // "A name"

format("a.otherProp: '{a.otherProp}'", data); // empty string

format("b.name: {b.name}", data); // Error (expected)

Trying to access b.name throws a TypeError (which is expected and properly handled). But accessing a.otherProp will just fail silently.

I think I will fork the library. Thanks for the help anyway :)

@steinerkelvin
Copy link
Author

Should I fork masteror tokenizer?

@davidchambers
Copy link
Owner

Fork master, I would say.

You're welcome to submit a pull request with your changes, though I won't necessarily accept it. The goal is to complete work on #2 and have the behaviour match Python's as closely as possible. Don't hold your breath for that, though. ;)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants