Skip to content

Instantly share code, notes, and snippets.

@evanleck
Created September 3, 2013 00:43
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/6418510 to your computer and use it in GitHub Desktop.
Save evanleck/6418510 to your computer and use it in GitHub Desktop.
Array.prototype.reduce shim for non-compliant browsers. Converted from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce.
# reduce from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce
if "function" isnt typeof Array::reduce
Array::reduce = (callback, opt_initialValue) ->
"use strict"
# At the moment all modern browsers, that support strict mode, have
# native implementation of Array.prototype.reduce. For instance, IE8
# does not support strict mode, so this check is actually useless.
throw new TypeError("Array.prototype.reduce called on null or undefined") if null is this or "undefined" is typeof this
throw new TypeError(callback + " is not a function") if "function" isnt typeof callback
index = 0
length = @length >>> 0
value = undefined
isValueSet = false
if 1 < arguments_.length
value = opt_initialValue
isValueSet = true
while length > index
continue unless @hasOwnProperty(index)
if isValueSet
value = callback(value, this[index], index, this)
else
value = this[index]
isValueSet = true
++index
throw new TypeError("Reduce of empty array with no initial value") unless isValueSet
value
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment