Javascript字符串变体

时间:2017-10-25 07:17:45

标签: javascript python

我想创建一个包含输入和规则集的所有变体的数组。类似于js中的这个python代码: String Variations

E.g。

var input = 'Miami Vice Slow', rules = [['l','i'], ['i','l']]

应该给:

result = ['Miami Vice Slow', 'Mlami Vice Slow', 'Miaml Vice Slow', 'Miami Vlce Slow', 'Mlaml Vice Slow',....,'Miami Vice Siow', 'Mlami Vice Siow'...]

我重写了python脚本,但我不确定in的最后一部分

var Variator = (function() {
  function Variator(options) {
    for (key in options) {
      this[key] = options[key];
    }
  }

  Variator.prototype.applyRules = function(rules, input, start) {
    let prefix = "";
    let suffix = "";
    let replace = "";

    for (i = 0, len = rules.length; i < len; i++) {
      match = rules[i][0];
      replace = rules[i][1];

      console.log("match", match, "replace", replace);
      index = input.indexOf(match, start);
      if (index < 0)
        //No match -- skip to next one
        continue
      //# Prepare the result of the replacement.
      prefix = input.substring(start, index) + replace;
      console.log("prefix",prefix);
      //Apply further rules to the rest of the string by a recursive call.
      for ( suffix in this.applyRules(rules, input, index + match.length) ) {
        return prefix + suffix;
      }

    }
  }

  Variator.prototype.variate = function() {
    let rules = [["l","i"], ["i","l"]];
    return this.applyRules(rules, "Slow Miami Vice", 0)
  };

  return Variator;
})();

module.exports = Variator;

0 个答案:

没有答案