title: Codility Peak JavaScript Implementation
body: <p>I am working on the <a href="https://codility.com/programmers/lessons/10-prime_and_composite_numbers/peaks/" rel="nofollow noreferrer">Codility Peak problem</a>:</p>
  
  <blockquote>
    <p>Divide an array into the maximum number of same-sized blocks, each of which should contain an index <em>P</em> such that <em>A[P - 1] &lt; A[P] > A[P + 1]</em>.</p>
  </blockquote>
  
  <p>My own solution is provided below, but it only scores 45%. So my question is:</p>
  
  <p>How can I still improve my solution?</p>
  
  <p>The code snippet seems to be long, since I added some extra comments to make myself clearer:</p>
  
  <pre><code>function solution(A) {
    var storage = [], counter = 0;
    // 1. So first I used a loop to find all the peaks
    // and stored them all into an array called storage
    for(var i = 1; i &lt; A.length - 1; i++) {
      if (A[i] &gt; A[i-1] &amp;&amp; A[i] &gt; A[i+1]) {
          storage.push(i);
      }
    }
    // 2. Go and write the function canBeSeparatedInto
    // 3. Use the for loop to check the counter
    for(var j = 1; j &lt; A.length; j++) {
      if (canBeSeparatedInto(j, A, storage)) {
        counter = j;
      }
    }
    return counter;
  }
  
  /* this function tells if it is possible to divide the given array into given parts
   * we will be passing our function with parameters: 
   * @param parts[number]: number of parts that we intend to divide the array into
   * @param array[array]: the original array
   * @param peaks[array]: an storage array that store all the index of the peaks
   * @return [boolean]: true if the given array can be divided into given parts
   */
  function canBeSeparatedInto(parts, array, peaks) {
      var i = 1, result = false;
      var blockSize = array.length / parts;
      peaks.forEach(function(elem) {
      // test to see if there is an element in the array belongs to the ith part
          if ((elem+1)/blockSize &lt;= i &amp;&amp; (elem+1)/blockSize&gt; i-1) {
              i++;
          }
      });
      // set the result to true if there are indeed peaks for every parts
      if (i &gt; parts) {
          result = true;
      }
      return result;
  }
  </code></pre>
  
  <p>The main problem with my code is that it does not pass the performance test. Could you give me some hint on that?</p>