Skip to content

Instantly share code, notes, and snippets.

@evanleck
Created September 3, 2013 00:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save evanleck/6418533 to your computer and use it in GitHub Desktop.
Save evanleck/6418533 to your computer and use it in GitHub Desktop.
Shim for basic statistical analysis methods on Array. Includes max, min, median, sum, mean, variance, and standard deviation.
# max
if "function" isnt typeof Array::max
Array::max = ->
"use strict"
# throw on null
throw new TypeError("Array.prototype.max called on null or undefined") if null is this or "undefined" is typeof this
Math.max.apply null, this
# min
if "function" isnt typeof Array::min
Array::min = ->
"use strict"
# throw on null
throw new TypeError("Array.prototype.min called on null or undefined") if null is this or "undefined" is typeof this
Math.min.apply null, this
# median
if "function" isnt typeof Array::median
Array::median = ->
"use strict"
# throw on null
throw new TypeError("Array.prototype.median called on null or undefined") if null is this or "undefined" is typeof this
# locals
sorted = @sort (a,b) => return a - b
length = @length >>> 0
half = Math.floor length/2
if length % 2
return this[half]
else
return [this[half - 1], this[half]].mean()
# sum
# depends on Array.prototype.reduce to work properly.
# shim for that available here https://gist.github.com/l3ck/6418510
if "function" isnt typeof Array::sum
Array::sum = ->
"use strict"
# throw on null
throw new TypeError("Array.prototype.sum called on null or undefined") if null is this or "undefined" is typeof this
@reduce (a, b) ->
a + b
# mean
if "function" isnt typeof Array::mean
Array::mean = ->
"use strict"
# throw on null
throw new TypeError("Array.prototype.mean called on null or undefined") if null is this or "undefined" is typeof this
length = @length >>> 0
@sum()/length
# variance
if "function" isnt typeof Array::variance
Array::variance = ->
"use strict"
# throw on null
throw new TypeError("Array.prototype.variance called on null or undefined") if null is this or "undefined" is typeof this
index = 0
length = @length >>> 0
mean = @mean()
powed = []
# loop to generate powed
while length > index
continue unless @hasOwnProperty(index)
powed.push Math.pow(this[index] - mean, 2)
++index
# return mean of powed
powed.mean()
# standard deviation
if "function" isnt typeof Array::stddev
Array::stddev = ->
"use strict"
# throw on null
throw new TypeError("Array.prototype.stddev called on null or undefined") if null is this or "undefined" is typeof this
# square root of variance
Math.sqrt @variance()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment