title: How to dynamically generate class method names in an es6 class?
body: <p>I am trying to figure out if it’s possible to generate method names on an es6 class. Take for example the following example, a <code>Replacer</code>, which runs replacement rules from a ruleset: </p>
  
  <pre><code>let smileyRules = [
    { ascii: ':)',  unicode: ' ' },
    { ascii: '8)',  unicode: ' ' }
  ]
  
  class Replacer {
    constructor(rules){
      this.rules = rules
    }
  
    replace(text, from, to){
      this.rules.forEach(rule =&gt; text = text.replace(rule[from], rule[to])) 
      return text
    }
  }
  
  let smileyizer = new Replacer(smileyRules)
  
  smileyizer.replace(':)', 'ascii', 'unicode')
  // " "
  
  smileyizer.replace(':)', 'unicode', 'ascii')
  // ":)"
  </code></pre>
  
  <p>So that does what it’s supposed to, but I would also like to generate convenience methods that would work like this:</p>
  
  <pre><code>smileyizer.ascii2unicode(':)')
  </code></pre>
  
  <p>which would internally call </p>
  
  <pre><code>smileyizer.replace(':)', 'ascii', 'unicode')
  </code></pre>
  
  <p>Of course, I would want to enable <code>unicode2ascii</code> as well. (And in fact, the point of this whole thing is that it will be used with rulesets where each rule has perhaps a dozen keys, so that's a lot of convenience methods.)</p>
  
  <p>In my <code>Replacer</code> class, I expect to generate the methods with something akin to:</p>
  
  <pre><code>generate(){
    this.rules.map(firstRule =&gt;
      this.rules.map(secondRule =&gt; {
        // somehow create method called firstRule + '2' + secondRule 
      })
    }
  }
  </code></pre>
  
  <p>…and then I would call this from the constructor.</p>
  
  <p>I know it’s possible to create computed properties using bracket notation, but I can't figure out how I would do something equivalent from inside <em>another</em> method.</p>
  
  <p><strong>Solution (thanks @DShook)</strong> </p>
  
  <p>Here’s a working <code>generate</code> method:</p>
  
  <pre><code>  generate(){
      let names = Object.keys(this.rules[0])
      names.forEach(firstName =&gt;
        names.forEach(secondName =&gt; {
          let method = firstName + '2' + secondName
          this[method] = (text, from, to) =&gt; this.replace(text, firstName, secondName)
        })
      )
    }
  </code></pre>