JavaScript: Week 3 Recap

0 views
Skip to first unread message

Paul Barry

unread,
Jun 8, 2009, 10:40:09 PM6/8/09
to bmore-...@googlegroups.com
At tonight's meeting it was just Mark and I.  We decided to jump into some functional programming with JavaScript and the task we decided to tackle was implementing Ruby's Enumerable in JavaScript.  We got as far as doing each, eachWithIndex, collect (a.k.a map), and inject (a.k.a reduce/fold).  Here's what we came up with:

http://tinyurl.com/enumerable-js

For any of you functional programming aficionados out there (Phil?), we ran into a problem with inject (reduce/fold).  The question is: Is it possible to implement inject without using recursion?  I'm sure it is, but I couldn't figure out how.  The implementation includes a horribly inefficient version based on a horribly inefficient implementation of head/tail.  It blows up if you try to run it on an Array of 10000 elements.  I'm wondering, can it be implemented in terms of map?

Anyway, I might try to hack out a few more of those methods for fun, but for next week, I propose we jump into jQuery.  We can go over the DOM manipulation stuff, which is very functional and sort of the bread and butter of jQuery, and maybe tackle some AJAX as well.

Phil! Gold

unread,
Jun 9, 2009, 9:42:46 AM6/9/09
to bmore-...@googlegroups.com
* Paul Barry <paulj...@gmail.com> [2009-06-08 22:40 -0400]:

> For any of you functional programming aficionados out there (Phil?), we ran
> into a problem with inject (reduce/fold). The question is: Is it possible
> to implement inject without using recursion?

Can't resist a challenge.

Array.prototype.inject = function(init, f) {
var r = init
for(var i = 0; i < this.length; i++) {
r = f(r, this[i])
}
return r
}

> I'm wondering, can it be implemented in terms of map?

I don't think so; they return different things. (Think of it this way:
map always returns a list exactly as long as the list supplied to it, so
there's no way to pare it down to a single returned value.)

--
...computer contrarian of the first order... / http://aperiodic.net/phil/
PGP: 026A27F2 print: D200 5BDB FC4B B24A 9248 9F7A 4322 2D22 026A 27F2
--- --
<awkward> anyone around?
<Flav> no, we're all irregular polygons
-- seen on #debian
---- --- --

Paul Barry

unread,
Jun 9, 2009, 10:32:38 AM6/9/09
to bmore-...@googlegroups.com
Ah, right of course, I don't realize why I didn't think of that last night.  Here it is implemented in terms of each and also handling the case where there is only one argument to the function and the first value in the array should be used as the initial value:
Array.prototype.inject = function(init, f) {
  var r, argc = arguments.length
  argc == 1 ? f = init : r = init
  this.eachWithIndex(function(e,i){
    r = (i == 0 && argc == 1) ? e : f(r, e)
  })
  return r
}
See the gist for an example of using it: http://tinyurl.com/enumerable-js
Reply all
Reply to author
Forward
0 new messages