I'm trying to determine if a passed-in array is Ascending, Descending, Rotated Ascending, or Rotated Descending. Although the now commented out console.log("RA");
near the end of the overall function shows "RA" when an appropriate string is passed into the parameters for the parent solve
function, return "RA" is returning undefined
. The sample array I used for the arr
parameter in an invocation of solve
in the console is [4,5,6,1,2,3], a Rotated Ascending array.
I've tried declaring variables and using them in place of the literal return values, and have declared them in several different locations. I have checked out and followed relevant Stack Overflow posts.
function solve(arr){
let asc = arr.every(function (x, i) {
return i === 0 || x >= arr[i - 1];
});
let desc = arr.every(function (x, i) {
return i === 0 || x <= arr[i - 1];
});
if (asc){
return "A"
}
if (desc){
return "D"
}
if (!asc || !desc){
arr.forEach(function(el, i){
let rtdAsc = "RA"
let rtdDesc = "RD"
let ascFind = arr.find(function(el, i){
return el >= arr[i - 1]
})
let descFind = arr.find(function(el, i){
return el <= arr[i - 1];
})
if (ascFind && descFind){
if (el === ascFind && arr[i] === el && arr[i+1] > ascFind){
return rtdAsc
// console.log("RA")
} else if (el === ascFind && arr[i] === el && arr[i+1] < ascFind){
return rtdDesc
}
}
})
}
}
~~~~~~~~~~~
I expect the result of invoking the example `solve([4,5,6,1,2,3]);` to result in "RA" through return statements, as it does successfully through `console.log("RA");`
Your problem is that the part where you have console.log("RA")
and return "RA"
is inside the function inside arr.forEach(..)
. Thus, you are correctly returning "RA" to the function inside forEach
, but not returning anything to solve
.
To resolve this, put a retVal
before the forEach
function. See below.
function solve(arr) { let asc = arr.every(function(x, i) { return i === 0 || x >= arr[i - 1]; }); let desc = arr.every(function(x, i) { return i === 0 || x <= arr[i - 1]; }); if (asc) { return "A" } if (desc) { return "D" } let retVal = "none"; if (!asc || !desc) { arr.forEach(function(el, i) { let rtdAsc = "RA" let rtdDesc = "RD" let ascFind = arr.find(function(el, i) { return el >= arr[i - 1] }) let descFind = arr.find(function(el, i) { return el <= arr[i - 1]; }) if (ascFind && descFind) { if (el === ascFind && arr[i] === el && arr[i + 1] > ascFind) { console.log("RA"); retVal = "RA"; return; //not exactly necessary } else if (el === ascFind && arr[i] === el && arr[i + 1] < ascFind) { retVal = "RD"; return; //not exactly necessary } } }) } return retVal; } console.log(solve([4,5,6,1,2,3]));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.