[SOLVED] How to extract a function out of arr.map(elem => dict[elem])?

Issue

A function should do only one thing is considered a good practice when writing functions. However, I have a function that is already very minimal, but nevertheless I think it can be further extracted, but I don’t know how this can be done.

The following recode() function replaces array values according to a look-up dictionary.

function recode(arr, dict) {
    return arr.map(elem => dict[elem])
}

Example to how it works:

// input data to be recoded
const myArr = ['eggplant', 'tomato', 'carrot', 'cabbage'];

// look-up dictionary
const myDict = {
    eggplant: 'purple',
    tomato: 'red',
    carrot: 'orange',
};

const result1 = recode(myArr, myDict)
console.log(result1) // => ["purple", "red", "orange", undefined]

The way I see it, the current recode() function does two things:

  1. It matches by identity (you might have a better description than this), i.e., elem => dict[elem]; and
  2. it maps over arr

My question is whether I can extract an individual function for elem => dict[elem], and supply that function to arr.map(). I imagine something along the lines of:

// pseudo-code
function funcInner() {...}

function recode(arr, dict) {
    return arr.map(funcInner)
}

This way, I will have one function that does only the replacement, and another that only maps over arr.


EDIT


To address the comments, I would like to make an analogy. Let’s consider a function that doubles array values.

function doubleArray(arr) {
  return arr.map(x => x * 2)
}

Some folks here might say that doubleArray() is already doing one thing. However, we could still extract:

const doubleNumber = x => x * 2;

function doubleArray2(arr) {
  return arr.map(doubleNumber)
}

As far as I understand, doubleArray() did two things (double & map), whereas doubleArray2() does only one thing (map) and doubleNumber() does one thing (doubles). Therefore, doubleArray() is not a meaningless refactoring.

Furthermore, once we have a function that does one thing, it promotes more accurate unit tests we can write for it.

Lastly, if we translated this code to typescript (which I didn’t focus on in this question), then the input type in doubleNumber() is different than the input type in doubleArray(). So that’s another reason why I would prefer to extract.

I’m very new to javascript, but this is the way I understand it. So my question about recode() was within this context.

Solution

To answer your question:

function recode(arr, dict) {
    return arr.map(elem => funcInner(elem,dict));
};

function funcInner(elem, dict) {
    return dict[elem];
}

But i agree with the others commenting on you question, this may be a little overkill. Your choice.

Answered By – Daniel Tamas

Answer Checked By – Timothy Miller (BugsFixing Admin)

Leave a Reply

Your email address will not be published.