JavaScript array_reduce
Iteratively reduce the array to a single value via the callback.
1 2 3 4 56 7 8 9 1011 12 13 14 1516 17 18 19 2021 22 23 24 2526 27 28 | function array_reduce (a_input, callback) { // Iteratively reduce the array to a single value via the callback. // // version: 909.322 // discuss at: http://phpjs.org/functions/array_reduce // + original by: Alfonso Jimenez (http://www.alfonsojimenez.com) // % note 1: Takes a function as an argument, not a function's name // * example 1: array_reduce([1, 2, 3, 4, 5], function (v, w){v += w;return v;}); // * returns 1: 15 var lon = a_input.length; var res = 0, i = 0; var tmp = []; for (i = 0; i < lon; i+=2) { tmp[0] = a_input[i]; if (a_input[(i+1)]) { tmp[1] = a_input[(i+1)]; } else { tmp[1] = 0; } res+= callback.apply(null, tmp); tmp = []; } return res; } |
Examples
Running
1 | array_reduce([1, 2, 3, 4, 5], function (v, w){v += w;return v;}); |
Should return
1 | 15 |
Dependencies
No dependencies, you can use this function standalone.
Open syntax issues
php.js uses JsLint to help us keep our code consistent and prevent some common bugs.
Eventually we want all code to pass or at least take into consideration most fixes suggested by JsLint, following this JsLint configuration we’ve decided on.
Authors
Thanks to the following developers, you get to have array_reduce goodness in JavaScript.
Arggg I made an error in the last example! It's "is" instead of "mi" :) If you realize "mi" is not in the string "This is a Simple text".
I'll try to develop another contribution soon :)
Regards!
@ Alfonso Jiménez: Hi Alfonso, thanks for your second contribution & the example! Only one thing, the example produces: false instead of: 'is is a Simple text.'
Maybe you can see what's going wrong?
(btw, I had to add the '{' & '}' to make it compatible with the packer)
BTW, Usage example:
1 | strpbrk('This is a Simple text', 'mi') |
Regards! Alfonso Jiménez (http://www.alfonsojimenez.com)
Hey Kevin. My second contribution is here :)
1 2 3 4 56 7 8 9 1011 12 13 14 1516 17 18 19 2021 22 23 24 2526 27 28 29 3031 32 | function strpbrk(haystack, char_list) { var lon = haystack.length; var lon_search = char_list.length; var ret = false; var stack = ''; if(lon >= lon_search) { if(lon == lon_search) { if(haystack == char_list) ret = haystack; } else { j = 0; i = 0; while(i < lon_search && j < lon && !ret) { if(char_list[i] == haystack[j]) { i++; if(i == lon_search) ret = true; } j++; } if(ret) for(i = (j-lon_search); i < lon; i++) stack += haystack[i]; if(stack != '') ret = stack; } } return ret; } |
Re


Kevin van Zonneveld
5 Mar '08
http://kevin.vanzonneveld.net/pj_tester.php
thanks again!