The code below was inspired by this post in Code Review.
Here is how it was first intended by its author:

I have the following code that converts a string that looks like : aaa-bbb|ccc-ddd|eee-fff to two strings that look like aaa|ccc|eee and bbb|ddd|fff

Somebody already proposed an answer, and I found it could be more improved using reduce() and map() methods.
But after a few time I realized it could be made of more general use, so I hooked in the intent to have a code which both:

  • accept any main- and sub-separator (| and -) in the above example.
  • accept any number of main parts and sub-parts, the only (not checked) requirement being the number of sub-parts is the same through all parts.
  • is strictly written functional-programming style

Then I end up with pretty different requirements than in the original post I cited, so rather than an answer I prefer to post it as a question, waiting for comments about:

  • is there a simpler strategy for doing that in functional style?
  • and even is it a good idea to use functional style, since it might be actually slower than with procedural code?

function reformat(string, mainSep, subSep) {
  return string.split(mainSep).map(item => item.split(subSep)).reduce(
    (result, part) => 
      part.map((str, index) => 
  ).join(subSep || ' ');

console.log(reformat('HEL-CAS|MAD-STO|XXX-YYY', '|', '-')); 
console.log(reformat('1:2:3_one:two:free_ONE:TWO:THREE_I:II:III', '_', ':'));
console.log(reformat('abcdefgh.ABCDEFGH', '.', ''));


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.