Ad
  • Custom User Avatar

    Out of curiosity I ran a performance test comparing normal division with the division by bitwise shift in this case:

    https://jsperf.com/numsum-division

    The bitwise division is a little faster.

  • Custom User Avatar

    Very clever. I like the use of the shift operator to do the division.

  • Custom User Avatar

    Just an alternative to shorten it a bit.

    The two cases are:

    1. The string has an even number of characters

    2. The string has an odd number of characters.

    If the string has an even number of characters we start the slicing one position early.

    We can subtract !(str.length % 2) from the starting position, str.length / 2.

    !(str.length % 2) === 1 if even, 0 if odd

  • Custom User Avatar

    Little math trick:

    The sum of the first n natural numbers is equal to n(n + 1)/2