0

I'm wondering if it's possible to write the following as concisely as possible in Javascript/Typescript:

a = a.trim()
b = b.trim()
c = c.trim()
...

As a one-liner I can write it like this:

[a, b, c, ...] = [a, b, c, ...].map(s => s.trim())

But even this can get messy if we're attempting to do this with 10 or 20+ variables. My specific use case: I've extracted several fields from a document under various variable names and I want to clean up each one by trimming unnecessary whitespace from each. Is there a more concise way than those above?

aki
  • 164
  • 1
  • 1
  • 12
  • Can you not trim during the extraction process? – Nick Jun 02 '20 at 03:17
  • The problem is that you have distinct vars `a`, `b`, `c` and more. If these were in an array, object or another appropriate data structure, then your proposed approach would be fine and you'd never need to pack and unpack all of these variables every time you need to apply an action to all of them. When you call functions, are you passing 10 to 20 parameters into them as well? Time for a redesign, I'd say. – ggorlen Jun 02 '20 at 03:19
  • @Nick, I think that is a solution to the underlying problem in most cases, I didn't go with that approach because of such cases as `[a, b, c] = parsedText.split(' - ')`, where we are performing additional operations after parsing, after which we would want to trim the output. – aki Jun 02 '20 at 04:46
  • @ggorlen because I export the data as an object, I ended up iterating through the entries and trimming values before returning it - similar to the solution in the link you posted :) The one-liner looked something like this: `Object.entries(obj).forEach(([k, v]) => obj[k] = v.trim());` – aki Jun 02 '20 at 04:47
  • @AkshathSivaprasad `[a, b, c] = parsedText.split(' - ').map(s => s.trim())` would work fine for that scenario – Nick Jun 02 '20 at 04:51
  • @Nick but that + other fields `d = 'hello ', e = ' world', ...` makes it somewhat more complex to apply the same approach everywhere, hence leading to my question – aki Jun 02 '20 at 04:54

0 Answers0