0

I have the following function.

from here Efficiently replace all accented characters in a string?

function test() {
  let aa = 'čǧǩőšűžČǦǨŐŠŰŽ'

  const ccc = wontParse(aa)
  console.log(ccc)

}

var wontParse = (function () {
  let in_chrs   = 'čǧǩőšűžČǦǨŐŠŰŽ',
      out_chrs  = 'cgkosuzCGKOSUZ', 
      chars_rgx = new RegExp('[' + in_chrs + ']', 'g'),
      transl    = {}, i,
      lookup    = function (m) { return transl[m] || m; };

  for (i=0; i<in_chrs.length; i++) {
    transl[ in_chrs[i] ] = out_chrs[i];
  }

  return function (s) { return s.replace(chars_rgx, lookup); }
})();

I want to edit the function, so to accept two additional parameters so as to call it like so:

function test() {
  let x  = 'čǧǩőšűžČǦǨŐŠŰŽ',
      y  = 'cgkosuzCGKOSUZ';

  let aa = 'čǧǩőšűžČǦǨŐŠŰŽ'

  const ccc = wontParse(aa,x,y)
  console.log(ccc)

}

I got this to work

var wontParse2 = (in_chrs,out_chrs) => (function () {
  let chars_rgx = new RegExp('[' + in_chrs + ']', 'g'),
      transl    = {}, i,
      lookup    = function (m) { return transl[m] || m; };

  for (i=0; i<in_chrs.length; i++) {
    transl[ in_chrs[i] ] = out_chrs[i];
  }

  return function (s) { return s.replace(chars_rgx, lookup); }
})();

So I can call it like this const ccc = wontParse(x,y)(aa)

But how to edit the function so it can be called like this? const ccc = wontParse(aa,x,y)

I do not understand the function well enough to do so particularly this

transl    = {}, i,
lookup    = function (m) { return transl[m] || m; };

and the last ()

Einarr
  • 214
  • 2
  • 14

1 Answers1

1

You're basically just moving the s parameter into the original call. Then you just return s.replace(...) as you did before. You also don't need to wrap the body in an IIFE.

var wontParse2 = (s, in_chrs, out_chrs) => {
  let chars_rgx = new RegExp("[" + in_chrs + "]", "g"),
    transl = {},
    i,
    lookup = function (m) {
      return transl[m] || m;
    };

  for (i = 0; i < in_chrs.length; i++) {
    transl[in_chrs[i]] = out_chrs[i];
  }

  return s.replace(chars_rgx, lookup);
};
kelsny
  • 23,009
  • 3
  • 19
  • 48