Lawrence123
Lawrence123

Reputation: 13

Javascript, Apply map function but with two possible functions

I'm currently working on a project that will require me to take a list of lengths (from a machine) and convert them into a list of timings. The machine can operate at two different speeds, of which I have denoted with either an 'F' before values of the faster speed and no 'F' before values at the slower speed. This is an example of my array of values: [1.234,2.13,F1.23,5.5,F2.3] To convert these into timings, I will need to divide every element that does NOT have and F in front, by 10, and every element that DOES have an F in front, by 100, and remove the F. The expected array outcome should look something like: [0.1234,0.213,0.0123,0.55,0.023]

I know how to use map functions, which would work if I only wanted to apply one function, such as .map[x => x/10]. I'm also aware I could use for loops, but I started this project as a way to learn other methods that do not use these.. I'm very unsure on how I could apply another function, based on the starting character, but not to every element. Perhaps there is a command that I am missing that could work here?

Upvotes: 0

Views: 545

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1074138

While you could use separate map callbacks to do this, the usual solution would be to branch or use a conditional within a single map callback instead.

.map(x => x.charAt(0) === "F" ? +x.substring(1) : x / 10)

or with separate functions, defined elsewhere:

.map(x => x.charAt(0) === "F" ? convertF(x) : convertNonF(x))

If you want to do it with two map callbacks instead, there are various ways to do that, but they're all more complicated than the above, and nearly all of them involve branching/conditionals anyway (the only one I can think of offhand that doesn't use branching/conditionals is really overcomplicated, involving an intermediate array of [index, value] pairs, two filter calls, and various other overhead).

Upvotes: 1

Related Questions