Skip to content

Instantly share code, notes, and snippets.

@arextar
Forked from 140bytes/LICENSE.txt
Created September 27, 2011 21:00
Show Gist options
  • Save arextar/1246238 to your computer and use it in GitHub Desktop.
Save arextar/1246238 to your computer and use it in GitHub Desktop.
Summation function
function(
a, //Lower bound
b, //Upper bound
c, //[Step function]
d, //Multiply
e,f //Placeholders
){
c===true&&(d=c,c=0); //If c is true, use c as the 'multiply' param
if(a==1&&!c&&!d) return (b*b+b)/2 //If it's a standard summation of 1..n, optimize
for(
e=!!d //initiate counter as d (will coerce to 0 if adding, 1 if multiplying)
;a<=b; //While lower bound is less than the upper bound...
f=c?c(b):b, //If a step function is passed, use it
d?e*=f:e+=f, //Perform the necessary operation
b-- //Decrement the upper bound
);
return e; //Return the result of the summation
}
function(a,b,c,d,e,f){c===!0&&(d=c,c=0);if(a==1&&!c&&!d)return(b*b+b)/2;for(e=!!d;a<=b;f=c?c(b):b,d?e*=f:e+=f,b--);return e}
DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
Version 2, December 2004
Copyright (C) 2011 YOUR_NAME_HERE <YOUR_URL_HERE>
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": "summation",
"description": "A function to execute a summation in JavaScript. Support for a step function and multiplication",
"keywords": [
"math"
]
}
<!DOCTYPE html>
<title>Summation</title>
<div>Expected value: <b>[5050, 5049, -15, 120]</b></div>
<div>Actual value: <b id="ret"></b></div>
<script>
var summate = function(a,b,c,d,e,f){c===!0&&(d=c,c=0);if(a==1&&!c&&!d)return(b*b+b)/2;for(e=!!d;a<=b;f=c?c(b):b,d?e*=f:e+=f,b--);return e}
document.getElementById( "ret" ).innerHTML = "["+[
summate(1,100),
summate(2,100),
summate(1,5,function(n){
return -n;
}),
summate(1,5,true)].join(", ")+"]"
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment