string-format icon indicating copy to clipboard operation
string-format copied to clipboard

applying transformer on all placeholders

Open steinerkelvin opened this issue 9 years ago • 4 comments

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.

steinerkelvin avatar May 09 '16 23:05 steinerkelvin

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. :)

davidchambers avatar May 10 '16 23:05 davidchambers

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 avatar May 11 '16 13:05 steinerkelvin

Should I fork masteror tokenizer?

steinerkelvin avatar May 11 '16 13:05 steinerkelvin

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. ;)

davidchambers avatar May 12 '16 00:05 davidchambers