Find all starting indices in a string which are anagrams of a word The task:


  Given a word W and a string S, find all starting indices in S which
  are anagrams of W.
  
  For example, given that W is "ab", and S is "abxaba", return 0, 3, and
  4.


My solution:



    const anagramOccurrencesOf = (w, s) =&gt; {
      const occurrencesCopy = [];
      let sCopy = s.slice(0);
    
      let index = 0;
      while (sCopy.length &amp;&amp; index !== -1) {
        index = sCopy.indexOf(w);
        if (index === -1) { break; }
        occurrencesCopy.push((occurrencesCopy[occurrencesCopy.length - 1] + index + 1 || 0));
        sCopy = sCopy.slice(index + 1);
      }
      const occurrencesReverse = [];
      let sReverse = s.split('').reverse().join('');
    
      index = 0;
      while (sReverse.length &amp;&amp; index !== -1) {
        index = sReverse.indexOf(w);
        if (index === -1) { break; }
        occurrencesReverse.push( (occurrencesReverse[occurrencesReverse.length - 1] - w.length - index + 1) || s.length - w.length);
        sReverse = sReverse.slice(index + 1);
      }
    
      return [...occurrencesCopy, ...occurrencesReverse].sort((a,b) =&gt; a -b);
    };
    
    console.log(anagramOccurrencesOf("ab", "abxaba"));




EDIT: The solution above would find indexes of palindromes. The solution below should find indexes of anagrams:



const sortAlphabetically = x =&gt; x.toLowerCase().split('').sort().join('')
const getIndexOfAnagramIn = (s, w) =&gt; {
  const wSorted = sortAlphabetically(w);
  const result = []
  for (let i = 0; i &lt; s.length + 1 - w.length; i++) {
    if (sortAlphabetically(s.slice(i, i + w.length)) === wSorted) {
      result.push(i);
    }
  }
  return result;
}

console.log(getIndexOfAnagramIn('abxaba', 'ab'));
This code looks pretty good. I don't see much I would change. This code makes good use of const and let where appropriate.

The only thing that stands out is that splitting a string into an array can be done with the spread syntax instead of calling split().

The first instance:


let sReverse = s.split('').reverse().join('');



Could be changed to 

let sReverse = [...s].reverse().join('');


And the other instance:


const sortAlphabetically = x =&gt; x.toLowerCase().split('').sort().join('')



Could be changed to:

const sortAlphabetically = x =&gt; [...x.toLowerCase()].sort().join('')