title: Writing an inverse function in javascript?
body: <p>I ran into a situation at work today where I needed to write the inverse of a function that I had already written, but I found it inefficient to write the inverse manually because it seems like I would be repeating a lot of my code, and if I were to update the original function I would have to update the inverse with the corresponding changes. The function I am talking about looks something like this:</p>
  
  <pre><code>var f = function(id, str) {
    if (id === 0) {
      return str.substring(0, 4) + " " + str.substring(4, 8);
    } else if (id === 1) {
      return str.substring(0, 3) + "/" + str.substring(3, 8);
    } else if (id === 2) {
      return str.substring(0, 4) + "-" + str.substring(4, 8);
    } else if (id == 3) {
      return str.substring(0, 3) + "," + str.substring(3, 8);
    }
  }
  </code></pre>
  
  <p>So for example <code>f(0, "ABCDEFGH")</code> will return <code>"ABCD EFGH"</code>. I need an inverse function that uses the function <code>f(id, str)</code> to come up with inputs from the output. So <code>finverse(formattedStr)</code> should return a dictionary of the corresponding inputs. For example, <code>finverse("ABCD EFGH")</code> should return <code>{  id: 0, str: "ABCDEFGH" }</code>. Would it be possible to make use of the existing function <code>f</code> to write this inverse such that even if I were to update the original function with an extra "else if" clause, I wouldn't have to update <code>finverse</code>. In other words I do not want to manually construct <code>finverse</code> with if statements to map the outputs back to the inputs, rather I want to manipulate the original function somehow to come up with an inverse. Is this possible in javascript?</p>