Skip to content

Instantly share code, notes, and snippets.

@whoknows
Forked from 140bytes/LICENSE.txt
Created February 27, 2012 16:20
Show Gist options
  • Save whoknows/1925057 to your computer and use it in GitHub Desktop.
Save whoknows/1925057 to your computer and use it in GitHub Desktop.
140byt.es -- Javascript ArraySum

Javascript ArraySum

This is a simple array sum function for javascript in only 89 bytes !

I could have done an array prototype, witch would have remove the "is array" check, but i wanted to do it this way.

function (a //This is the array you want to sum
,b //Placeholder used as a counter
,c //Placeholder used as the total value
,d){ //Placeholder used to store the array length
d=a.length; //Storing array length, it's used twice so its shorter this way
return d? //First we check if a is an array
function(){ //If so we start the sum function
for(b=c=0; //Initialising b (counter) and c (sum)
b<d; //While b is lower than d (array length)
c+=a[b++]); //We put in c the actual value of a then increment b
return c }() //To finish we return c
:!1 //If a wasn't an array we return false
}
function(a,b,c,d){d=a.length;return d?function(){for(b=c=0;b<d;c+=a[b++]);return c}():!1}
DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
Version 2, December 2004
Copyright (C) 2011 GUILLAUME COSTE <@Guillaume_Coste>
Everyone is permitted to copy and distribute verbatim or modified
copies of this license document, and changing it is allowed as long
as the name is changed.
DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. You just DO WHAT THE FUCK YOU WANT TO.
{
"name": "JavascriptArraySum",
"description": "As its name say, it's an array sum function for javascript",
"keywords": [
"array",
"sum",
"arraysum",
"array sum",
"140bytes"
]
}
<!DOCTYPE html>
<title>Javascript ArraySum</title>
<div>Expected value: <b>38.4foo</b></div>
<div>Actual value: <b id="ret"></b></div>
<script>
var arraySum = function (a,b,c,d){d=a.length;return d?function(){for(b=c=0;b<d;c+=a[b++]);return c}():!1}
//We can use any type of data inside the array :
document.getElementById( "ret" ).innerHTML = arraySum([4,9,6,7,12.4,'foo'])
</script>
@minikomi
Copy link

minikomi commented Mar 5, 2012

@tsaniel Unfortunately it gives weird results for arrays with strings which include numbers before letters eg.

[1,"3dogs"] => 30001

So maybe it wasn't the right way to go in the first place 💔

function (a,b){for(b in a){a[b]=(a[b]-0)};return eval(a.join("+").replace("NaN", 0))}

@maettig
Copy link

maettig commented Mar 20, 2012

What about using map? It's a bit different from your approach but this is how I would do it.

function(a,c){c=0;return a.map&&a.map(function(b){c+=isNaN(b)?0:b})&&c}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment