Array reduce method

149 views
Skip to first unread message

Xavier Belanche Alonso

unread,
Aug 14, 2013, 5:57:28 AM8/14/13
to haxe...@googlegroups.com
I'm wondering if there's a way in Haxe to do the same of reduce method (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce). I guess that Lambdas, as I read at the documentation (functional fold, which is also known as reduce, accumulate, compress or inject.), could be the solution but I'm stuck. Any code snippet that helps me to understand it is welcome.

Thanks

Juraj Kirchheim

unread,
Aug 14, 2013, 9:02:49 AM8/14/13
to haxe...@googlegroups.com
To calculate a sum:

Lambda.fold(someArray, function (item, sum) return item + sum, 0);

Or more a bit nicer to read:

using Lambda;

someArray.fold(function (item, sum) return item + sum, 0);

Or the obvious way to do it:

var sum = 0;
for (item in someArray) sum += item;

I often have the impression that these "functional" array methods are
totally overused in JavaScript and the main reason for that is the
rather antiquated C-style for loop in combination with horrible
variable scoping. The last version is the fastest and also has the
least tokens. And it's also self-explanatory.
So while Lambda will give you what you want to do, I would point out
that not all that is "chic" in JavaScript is necessarily the best
thing to do in Haxe ;)

Regards,
Juraj

Xavier Belanche Alonso

unread,
Aug 14, 2013, 4:27:31 PM8/14/13
to haxe...@googlegroups.com
Oh! I see how it works now! and I'll keep your advice in mind ;)

Thanks!
Reply all
Reply to author
Forward
0 new messages