javascript counting valleys

Solutions on MaxInterview for javascript counting valleys by the best coders in the world

showing results for - "javascript counting valleys"
Angela
15 Apr 2019
1function countingValleys(n, s) {     
2  const min = 2;     
3  const max = 1000000;     
4  let isInValley = false;     
5  let valleys = 0;     
6  s = (typeof s === "string") ? s.split('') : s; 
7  
8  if (s.length >= min          
9      && s.length <= max          
10      && n === parseInt(n, 0)          
11      && n >= min          
12      && n <= max           
13      && n === s.length) {                    
14    
15    s.map(steps => ((steps === "U") ? 1 : -1))               
16      .reduce((prev, next) => {                    
17      if (prev < 0 && !isInValley) {                         
18        isInValley = true;                    
19      }                    
20      if ((prev + next) === 0 && isInValley) {                         
21        valleys++;                         
22        isInValley = false;                    
23      }            
24      
25      return prev + next;                   
26    });     
27  }    
28  
29  return valleys; 
30}