1

Fix a bug in a javascript given function

i have an assessment in which i have to find and fix a bug in a given javascript function , here is it:

The javascript function presented to you below contains a bug. Your goal is to find and fix it.

You must implement the convertToIntegers () function which takes an array of strings as a parameter.

Each of these strings represents an integer. The function must therefore parse them and return the list of these integers.

For example, convertToIntegers (["4", "7", "12"]) should return [4 , 7 , 12]

Note: To get the maximum score, you must continue to use the Array.map function

//Javascript code below
//This function doesn't work as expected
//find the error and fix it

function convertToIntegers(strings){

return strings.map(parseInt);

}

console.log(convertToIntegers(["1","2","3"]));  //[1,2,3]
console.log(convertToIntegers([]));   //[]
console.log(convertToIntegers(null));  // null

So i have found the bugs , here they are:

TypeError: Cannot read property 'map' of null and [ 1, NaN, NaN ]

So i fixed it by doing this:

function convertToIntegers(strings) {
        if (strings) {
            return strings.map((str) => parseInt(str));
            
        } else {
            return null;
        }

}
console.log(convertToIntegers(["1","2","3"]));
console.log(convertToIntegers([]));
console.log(convertToIntegers(null));

i have fix it , now it works

Submitted October 02nd 2021 by Admin

Answers
0

here's what you can do in an organised way:

function convertToIntegers(strings) { return strings && strings.map((s) => parseInt(s))
} // or (es6 one liner)
// const convertToIntegers = (strArr) => strArr && strArr.map((str) => parseInt(str)) console.log(convertToIntegers(["1", "2", "3"]));
console.log(convertToIntegers([]));
console.log(convertToIntegers(null));

Admin | 2 weeks ago


0

You can use this.

function convertToIntegers(strings) { if (strings) { return strings.map(str => parseInt(str)); } else { return null; }
}
console.log(convertToIntegers(["1","2","3"]));
console.log(convertToIntegers([]));
console.log(convertToIntegers(null));

Admin | 2 weeks ago


0

You could use a Number constructor with an array check

function convertToIntegers(strings) { return Array.isArray(strings) ? strings.map(Number) : null
} console.log(convertToIntegers(["1", "2", "3"]));
console.log(convertToIntegers([]));
console.log(convertToIntegers(null));

With short circuit operators, you could simplify this even further

function convertToIntegers(strings) { return strings?.map(Number) ?? null;
}

Admin | 2 weeks ago



Relevant Questions