Ad
  • Default User Avatar

    Array(x) creates an array of length x.
    Array.apply(null, Array(x)) equals Array.apply(null, [undefined, undefined, ..., undefined]), second part containing x undefined elements. This is equivalent to Array(undefined, undefined, ..., undefined), which produces an array with x elements and assigns undefined to each element.
    Then we call the map function for each, and for each element we assign it the value ++i. This means that for the first element it will have the value 1 (0 + 1), the second element will have the value 2 (1 + 1), and so on, up to xth element which will have the value x ((x - 1) + 1).
    Thus, in the end, we have created a range from 1 to x.

    One more note: in case you are wondering why not use just Array(x) instead of Array.apply(null, Array(x)), when both result into arrays of x elements, the explanation is related to the map usage. In the first case, the elements of the array are not set, while for the second one we have undefined set for each value. The map callback function is invoked only for indexes of the array which have assigned values, including undefined. It is not called for missing elements of the array (that is, indexes that have never been set, which have been deleted or which have never been assigned a value).

  • Custom User Avatar

    Thanks.
    First I map every element of the array with the result of this function

    a => a instanceOf Array? arraySum(a) : typeof a == 'number' ? a : 0
    

    If the element is an array, the function uses recursion to replace it with it's sum.
    Else if the element is a number it remains the same. If it is not a number, it is just replaced by 0 because we are supposed to ignore those elements.

    Now all that's needed to do is take the sum of the resultant array.

    This is achieved by the simple: reduce((a,b) => a+b, 0)

  • Custom User Avatar

    It's so clever! Can you explain this code?

  • Custom User Avatar

    Could you please explain how this code is work?) var range = Array.apply(null, Array(x)).map((_, i) => ++i);