The idea is to eliminate pointless travel in an array of directions:
'N' = North
'S' = South
'E' = East
'W' = West
So if we have the array ['S', 'E', 'W', 'W'], we'll want for the mapQuest function to return:
['S', 'W']
Since East and West are next to each-other, they'll cancel each-other out.
*NOTE The directions must be next to each-other in the array in order to get cancelled out.
Also, the array should continue to get reduced until the final array does not contain any opposites - i.e. it handles "complex cases":
['W', 'N', 'S', 'E', 'N']
should return
['N']
Because ['W', 'N', 'S', 'E', 'N'] => ['W', 'E', 'N'] => ['N']
Part of this challenge is that I must use the reduce method.
Based on my understanding of .reduce(), my thought is to do something like:
function mapQuest (array) {
return array.reduce((accumulator, current, i) => {
if ((array[i] === 'S' && array[i + 1] !== 'N' && array[i - 1] !== 'N')) {
accumulator.push(array[i]);
}
if ((array[i] === 'N' && array[i + 1] !== 'S' && array[i - 1] !== 'S')) {
accumulator.push(array[i]);
}
if ((array[i] === 'E' && array[i + 1] !== 'W' && array[i - 1] !== 'W')) {
accumulator.push(array[i]);
}
if ((array[i] === 'W' && array[i + 1] !== 'E' && array[i - 1] !== 'E')) {
accumulator.push(array[i]);
}
return accumulator;
}, []);
}
console.log(mapQuest(['S', 'E', 'W', 'W']));
Works but doesn't pass the last test-spec - handing complex situations.
Expect ['N', 'N', 'E', 'W', 'S', 'S', 'E', 'W', 'N', 'N', 'W', 'S', 'E'] to equal ['N', 'N', 'W', 'S', 'E']
matchis used for matching regular expressions. For equality comparison you can use justcurrent === 'S'. That way you can also avoid the check for undefined. - Slaiif ((current !== undefined && current === 'S' && current[i + 1] !== 'N' || (current !== undefined && current === 'N' && current[i + 1] !== 'S'))) { accumulator.push(current); }- SpeakInCode43return accumulator;after the if statements. Otherwise, the function returns undefined if nothing is returned, andaccumulatorbecomes undefined for the next values. If you are not familiar with how reduce works, I would recommend starting with the basic for loops first. Also, your if statements don't seem to be handling all cases. I think you need at least two more. - Slaifilterrather than reduce. - Slai