I'm currently working on a program in node, and part of my code looks like this:
function interpretRange(num, shorthand) {
let shorthandLength = shorthand.length
console.log(typeof num);
console.log(num.length);
...
When I run this code, passing '1' as the argument for num, I see the following in my console:
string
1
undefined
/Users/username/Documents/10. Programming/problem 4.js:78
console.log(num.length);
^
TypeError: Cannot read property 'length' of undefined
Any idea why this error could be happening? As you can see, i checked for the type of num and it's a string. And then when I print num to the console it works and prints 1 which is correct.
However, for some reason I'm still getting the type error (even after the value was printed to the console).
Edit: Full Code Here:
The error happens at num.length
function completeNumbers(shorthand) {
let ranges = shorthand.split(', ');
let longHand = [];
ranges.forEach(range => {
let interpreted = [];
let expanded = [];
range.split(/[-:..]/g)
.reduce((curr, shorthand) => { // What hapens if it's one number
interpreted.push([curr, interpretRange(curr, shorthand)])
})
console.log(interpreted);
interpreted.forEach(range => expanded.push(expandList(range)))
console.log(expanded)
})
}
function interpretRange(num, shorthand) {
let shorthandLength = shorthand.length
let baseNum = num.length === shorthand.length ? '0' : num.slice(0, -shorthandLength)
let compareNum = num.slice(-shorthandLength);
if (parseInt(shorthand) <= parseInt(compareNum)) {
return String(parseInt(baseNum) + 1) + shorthand;
} else {
return baseNum + shorthand;
}
};
completeNumbers("1:5:2, 3"); // 1, 2, 3, 4, 5, 6, ... 12
The problem is you don't return anything from the reduce, so the second iteration will have undefined as previousValue of the reduce function. That's why you're seeing this error (take a look at the doc of Reduce Function)
I don't know what you want to do actually but you have to return something inside the reduce function (according to what you want to do) or consider using map or simply a classic for loop