Talk:Array length

From Rosetta Code
Revision as of 16:22, 8 October 2015 by Hout (talk | contribs) (and we could probably cache the length and switch to if then else, too, whenever run-time outweighs coder time)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

JavaScript

I like the direction of rdm's suggestion about efficiency and the cost of folds (depending of course, on implementation - the Haskell prelude 'last' is a fold). ES6, which has put some work into tail-recursion optimisations, may be a bit better than ES5 as a vehicle for functional styles of code composition.

function last(list, defaultValue) {
   return list.length ?list[list.length-1] :defaultValue;
}

Taking it one step further, I guess one could also argue that, depending on implementation, two calls to the length function, though probably unlikely to involve two scans of the whole array, might also look a bit profligate.

Perhaps just cache it ?:

function last(list, defaultValue) {
    var lng = list.length,
        return lng ? list[lng-1] : defaultValue;
}

Though once we announce the start of the pre-optimisation season, we are probably also inviting someone to pop up and point out, quite correctly, that JS implementations of ternary expressions tend to be less efficient than their implementations of if then else statements :-) Hout (talk) 16:22, 8 October 2015 (UTC)