Skip to content

Instantly share code, notes, and snippets.

@jeremyckahn
Created September 12, 2011 00:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save jeremyckahn/1210378 to your computer and use it in GitHub Desktop.
Save jeremyckahn/1210378 to your computer and use it in GitHub Desktop.
Equivalent JS and CoffeeScript functions?
JS:
//////////
function getSpeedySignature (ofString) {
var sum
,len
,i;
sum = 0;
len = ofString.length;
for (i = 0; i < len; i++) {
sum += ofString.charCodeAt(i);
}
return sum;
}
CoffeeScript:
//////////
getSpeedySignature: (ofString) ->
sum = 0
len = ofString.length
return ofString.split('').reduce (prev, curr, i) ->
+prev + curr.charCodeAt(0)
,0
@TrevorBurnham
Copy link

Looks good! The only changes I'd make are 1) move the reduce callback out for readability (it's actually fewer lines that way, too), 2) ditch len since it's unused, and 3) ditch the explicit return. So:

getSpeedySignature = (ofString) ->
  sum = 0
  addCharCode = (prev, curr, i) -> +prev + curr.charCodeAt(0)
  ofString.split('').reduce addCharCode, 0

@jeremyckahn
Copy link
Author

Ohhh, that is much nicer. Nice, thanks for the critique! This is the first thing I've written in CoffeeScript, the syntax is quite nice (although it's a big departure from the C-style syntaxes I'm used to).

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