Time for the next installment in 256 JS Game Extensions. It’s been a while hasn’t it? Well don’t worry because here are four new crazy cool additions to the Array
class. This brings us up to 40!
Array::maxima = (valueFunction=Function.identity) -> @inject([-Infinity, []], (memo, item) -> value = valueFunction(item) [maxValue, maxItems] = memo if value > maxValue [value, [item]] else if value is maxValue [value, maxItems.concat(item)] else memo ).last() Array::maximum = (valueFunction) -> @maxima(valueFunction).first() Array::minima = (valueFunction=Function.identity) -> inverseFn = (x) -> -valueFunction(x) @maxima(inverseFn) Array::minimum = (valueFunction) -> @minima(valueFunction).first()
Array#maxima
is the core of this set, all the other methods are implemented based upon it. maxima
returns a list of the elements that have the maximum value for a given value function. The default value function is the identity function which returns the item itself. This will work great for integers or strings: anything that correctly works with the >
operator.
The value function can be overridden for example if you want to compute the maximum length word in a list you could pass in (word) -> word.length
The special case maximum
delegates to maxima
and returns only the first result. Similarly minima
delegates to maxima
but inverts the value function.
With these methods many problems that seem complex actually become quite a lot simpler by picking a value function and whether you want to maximize it or minimize it.