延迟ES6模板字面量的执行



我正在玩新的ES6模板文字功能,我想到的第一件事是JavaScript的String.format,所以我开始实现一个原型:

String.prototype.format = function() {
  var self = this;
  arguments.forEach(function(val,idx) {
    self["p"+idx] = val;
  });
  return this.toString();
};
console.log(`Hello, ${p0}. This is a ${p1}`.format("world", "test"));

ES6Fiddle

然而,在传递给我的原型方法之前,Template Literal会对进行计算。是否有任何方法我可以写上面的代码推迟结果,直到我已经动态创建的元素?

我可以看到三种方法:

  • 使用模板字符串,就像它们被设计用来使用一样,没有任何format函数:

    console.log(`Hello, ${"world"}. This is a ${"test"}`);
    // might make more sense with variables:
    var p0 = "world", p1 = "test";
    console.log(`Hello, ${p0}. This is a ${p1}`);
    

    甚至函数参数用于实际的求值延迟:

    const welcome = (p0, p1) => `Hello, ${p0}. This is a ${p1}`;
    console.log(welcome("world", "test"));
    
  • 不要使用模板字符串,而要使用普通字符串字面值:

    String.prototype.format = function() {
        var args = arguments;
        return this.replace(/${p(d)}/g, function(match, id) {
            return args[id];
        });
    };
    console.log("Hello, ${p0}. This is a ${p1}".format("world", "test"));
    
  • 使用带标签的模板文字。请注意,处理程序仍然会在没有拦截的情况下对替换进行评估,因此,如果没有名为so的变量,就不能使用p0这样的标识符。如果接受了不同的替换体语法建议,此行为可能会改变。

    function formatter(literals, ...substitutions) {
        return {
            format: function() {
                var out = [];
                for(var i=0, k=0; i < literals.length; i++) {
                    out[k++] = literals[i];
                    out[k++] = arguments[substitutions[i]];
                }
                out[k] = literals[i];
                return out.join("");
            }
        };
    }
    console.log(formatter`Hello, ${0}. This is a ${1}`.format("world", "test"));
    // Notice the number literals: ^               ^
    

扩展@Bergi的答案,当您意识到可以返回任何结果(而不仅仅是普通字符串)时,标记模板字符串的强大功能就会显示出来。在他的示例中,标记构造并返回一个具有闭包和函数属性format的对象。

在我最喜欢的方法中,我自己返回一个函数值,您可以稍后调用它并传递新参数来填充模板。这样的:

function fmt([fisrt, ...rest], ...tags) {
  return values => rest.reduce((acc, curr, i) => {
    return acc + values[tags[i]] + curr;
  }, fisrt);
}

或者,对于代码高尔夫球手:

let fmt=([f,...r],...t)=>v=>r.reduce((a,c,i)=>a+v[t[i]]+c,f)

然后构造模板并推迟替换:

> fmt`Test with ${0}, ${1}, ${2} and ${0} again`(['A', 'B', 'C']);
// 'Test with A, B, C and A again'
> template = fmt`Test with ${'foo'}, ${'bar'}, ${'baz'} and ${'foo'} again`
> template({ foo:'FOO', bar:'BAR' })
// 'Test with FOO, BAR, undefined and FOO again'

另一个选项,更接近你写的,是返回一个从字符串扩展的对象,使duck-typing开箱即用并尊重接口。String.prototype的扩展不起作用,因为您需要模板标记的闭包来稍后解析参数。

class FormatString extends String {
  // Some other custom extensions that don't need the template closure
}
function fmt([fisrt, ...rest], ...tags) {
  const str = new FormatString(rest.reduce((acc, curr, i) => `${acc}${${tags[i]}}${curr}`, fisrt));
  str.format = values => rest.reduce((acc, curr, i) => {
    return acc + values[tags[i]] + curr;
  }, fisrt);
  return str;
}

然后,在call-site:

> console.log(fmt`Hello, ${0}. This is a ${1}.`.format(["world", "test"]));
// Hello, world. This is a test.
> template = fmt`Hello, ${'foo'}. This is a ${'bar'}.`
> console.log(template)
// { [String: 'Hello, ${foo}. This is a ${bar}.'] format: [Function] }
> console.log(template.format({ foo: true, bar: null }))
// Hello, true. This is a null.

AFAIS,有用的功能"延迟执行字符串模板"仍然不可用。然而,使用lambda是一种表达性强、易读且简短的解决方案:

var greetingTmpl = (...p)=>`Hello, ${p[0]}. This is a ${p[1]}`;
console.log( greetingTmpl("world","test") );
console.log( greetingTmpl("@CodingIntrigue","try") );

您可以使用下面的函数

向字符串注入值
let inject = (str, obj) => str.replace(/${(.*?)}/g, (x,g)=> obj[g]);

let inject = (str, obj) => str.replace(/${(.*?)}/g, (x,g)=> obj[g]);

// --- Examples ---
// parameters in object
let t1 = 'My name is ${name}, I am ${age}. My brother name is also ${name}.';
let r1 = inject(t1, {name: 'JOHN',age: 23} );
console.log("OBJECT:", r1);

// parameters in array
let t2 = "Today ${0} saw ${2} at shop ${1} times - ${0} was haapy."
let r2 = inject(t2, {...['JOHN', 6, 'SUsAN']} );
console.log("ARRAY :", r2);

我也喜欢String.format函数的想法,并且能够显式地定义分辨率变量。

这是我想到的…基本上是String.replace方法和deepObject查找。

const isUndefined = o => typeof o === 'undefined'
const nvl = (o, valueIfUndefined) => isUndefined(o) ? valueIfUndefined : o
// gets a deep value from an object, given a 'path'.
const getDeepValue = (obj, path) =>
  path
    .replace(/[|].?/g, '.')
    .split('.')
    .filter(s => s)
    .reduce((acc, val) => acc && acc[val], obj)
// given a string, resolves all template variables.
const resolveTemplate = (str, variables) => {
  return str.replace(/${([^}]+)}/g, (m, g1) =>
            nvl(getDeepValue(variables, g1), m))
}
// add a 'format' method to the String prototype.
String.prototype.format = function(variables) {
  return resolveTemplate(this, variables)
}
// setup variables for resolution...
var variables = {}
variables['top level'] = 'Foo'
variables['deep object'] = {text:'Bar'}
var aGlobalVariable = 'Dog'
// ==> Foo Bar <==
console.log('==> ${top level} ${deep object.text} <=='.format(variables))
// ==> Dog Dog <==
console.log('==> ${aGlobalVariable} ${aGlobalVariable} <=='.format(this))
// ==> ${not an object.text} <==
console.log('==> ${not an object.text} <=='.format(variables))

或者,如果你想要的不仅仅是变量解析(例如模板字面量的行为),你可以使用下面的。

注意: eval被认为是"邪恶的"-考虑使用safe-eval替代。

// evalutes with a provided 'this' context.
const evalWithContext = (string, context) => function(s){
    return eval(s);
  }.call(context, string)
// given a string, resolves all template variables.
const resolveTemplate = function(str, variables) {
  return str.replace(/${([^}]+)}/g, (m, g1) => evalWithContext(g1, variables))
}
// add a 'format' method to the String prototype.
String.prototype.format = function(variables) {
  return resolveTemplate(this, variables)
}
// ==> 5Foobar <==
console.log('==> ${1 + 4 + this.someVal} <=='.format({someVal: 'Foobar'}))

我发布了一个类似问题的答案,给出了两种延迟模板字面量执行的方法。当模板文字位于函数中时,只有在调用函数时才计算模板文字,并且使用函数的作用域对其进行计算。

https://stackoverflow.com/a/49539260/188963

虽然这个问题已经得到了回答,但在这里我有一个简单的实现,我在加载配置文件时使用(代码是typescript,但它很容易转换成JS,只需删除类型):

/**
 * This approach has many limitations:
 *   - it does not accept variable names with numbers or other symbols (relatively easy to fix)
 *   - it does not accept arbitrary expressions (quite difficult to fix)
 */
function deferredTemplateLiteral(template: string, env: { [key: string]: string | undefined }): string {
  const varsMatcher = /${([a-zA-Z_]+)}/
  const globalVarsmatcher = /${[a-zA-Z_]+}/g
  const varMatches: string[] = template.match(globalVarsmatcher) ?? []
  const templateVarNames = varMatches.map(v => v.match(varsMatcher)?.[1] ?? '')
  const templateValues: (string | undefined)[] = templateVarNames.map(v => env[v])
  const templateInterpolator = new Function(...[...templateVarNames, `return `${template}`;`])
  return templateInterpolator(...templateValues)
}
// Usage:
deferredTemplateLiteral("hello ${thing}", {thing: "world"}) === "hello world"

尽管有可能使这个东西更强大&灵活,它带来了太多的复杂性和风险,没有多少好处。

要点链接:https://gist.github.com/castarco/94c5385539cf4d7104cc4d3513c14f55

(参见上面@Bergi的非常相似的答案)

function interpolate(strings, ...positions) {
  var errors = positions.filter(pos=>~~pos!==pos);
  if (errors.length) {
    throw "Invalid Interpolation Positions: " + errors.join(', ');
  }
  return function $(...vals) {
    var output = '';
    for (let i = 0; i < positions.length; i ++) {
      output += (strings[i] || '') + (vals[positions[i] - 1] || '');
    }
    output += strings[strings.length - 1];
    return output;
  };
}
var iString = interpolate`This is ${1}, which is pretty ${2} and ${3}. Just to reiterate, ${1} is ${2}! (nothing ${0} ${100} here)`;
// Sets iString to an interpolation function
console.log(iString('interpolation', 'cool', 'useful', 'extra'));
// Substitutes the values into the iString and returns:
//   'This is interpolation, which is pretty cool and useful.
//   Just to reiterate, interpolation is cool! (nothing  here)'

这个和@Bergi的回答的主要区别在于如何处理错误(无声的vs不)。

将这个想法扩展为接受命名参数的语法应该很容易:

interpolate`This is ${'foo'}, which is pretty ${'bar'}.`({foo: 'interpolation', bar: 'cool'});
https://github.com/spikesagal/es6interpolate/blob/main/src/interpolate.js

最新更新