2
\$\begingroup\$

I've been doing quite a few code golf recently and I realised that a lot of times, I have to do something involving list.

Most of the times lists are space-separated or comma-separated values in the first argument (argv[2]), and the return value should also be a space/comma-separated string.

Are there any tips for converting comma/space-separated to array and back to comma/space-separated values ?

Here's what I know so far:

Array => String

["foo","bar","baz"].join() // Default argument is ","
["foo","bar","baz"].join` ` // ES6 backtick syntax
["foo","bar","baz"]+"" // Equivalent of toString(): return comma-separated values

String => Array

"foo,bar,baz".split`,` // ES6 backtick syntax

So are they other shorter ways of doing it or problem-specific solutions that doesn't require conversion from string to array and back to string ?

\$\endgroup\$
3
  • 1
    \$\begingroup\$ Why not simply take input and return output as lists? \$\endgroup\$
    – Adám
    Nov 22, 2021 at 10:04
  • \$\begingroup\$ What do you mean ? \$\endgroup\$
    – CreaZyp154
    Nov 22, 2021 at 12:05
  • 4
    \$\begingroup\$ Your problem seems to be stemming from getting a list in text form, and wanting to return a list as text form, but according to default I/O rules, you can write a function that deals with actual lists. \$\endgroup\$
    – Adám
    Nov 22, 2021 at 12:17

2 Answers 2

2
\$\begingroup\$

eval

For array of numbers, eval may work.

s.split(',')
eval(`[${s}]`)

Although code above is a bit longer, but there are some extra benefits via eval:

  • eval returns number[] instead of string[], and you can add them easier.
  • eval provide an extra () pair. You may write some codes in the eval string, in the eval brackets, and also after the eval.
\$\endgroup\$
0
1
\$\begingroup\$

String.prototype.replace

If you want a simple Array#map, you may use String#replace instead.

s.split`,`.map(v=>f(v))+''      // comma split and join
s.replace(/[^,]+/g,v=>f(v))     // comma separated
s.replace(/\w+/g,v=>f(v))       // comma separated

s.split` `.map(v=>f(v)).join` ` // space split and join
s.replace(/\S+/g,v=>f(v))       // space separated

String#replace may be shorter if you can find a short RegExp. /[^,]+/ is a bit longer, but if /\w+/ is acceptable, it could be shorter.

But be notice that the 2nd parameter of replace callback is the position by character instead of position in array.

You may also use some capture groups to parse the string in it.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.