UNPKG

phpjs

Version:

php.js offers community built php functions in javascript

96 lines (81 loc) 2.87 kB
--- layout: page title: "JavaScript array_map function" comments: true sharing: true footer: true alias: - /functions/view/array_map:325 - /functions/view/array_map - /functions/view/325 - /functions/array_map:325 - /functions/325 --- <!-- Generated by Rakefile:build --> A JavaScript equivalent of PHP's array_map {% codeblock array/array_map.js lang:js https://raw.github.com/kvz/phpjs/master/functions/array/array_map.js raw on github %} function array_map (callback) { // From: http://phpjs.org/functions // + original by: Andrea Giammarchi (http://webreflection.blogspot.com) // + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) // + input by: thekid // + improved by: Brett Zamir (http://brett-zamir.me) // % note 1: If the callback is a string (or object, if an array is supplied), it can only work if the function name is in the global context // * example 1: array_map( function (a){return (a * a * a)}, [1, 2, 3, 4, 5] ); // * returns 1: [ 1, 8, 27, 64, 125 ] var argc = arguments.length, argv = arguments, glbl = this.window, obj = null, cb = callback, j = argv[1].length, i = 0, k = 1, m = 0, tmp = [], tmp_ar = []; while (i < j) { while (k < argc) { tmp[m++] = argv[k++][i]; } m = 0; k = 1; if (callback) { if (typeof callback === 'string') { cb = glbl[callback]; } else if (typeof callback === 'object' && callback.length) { obj = typeof callback[0] === 'string' ? glbl[callback[0]] : callback[0]; if (typeof obj === 'undefined') { throw 'Object not found: ' + callback[0]; } cb = typeof callback[1] === 'string' ? obj[callback[1]] : callback[1]; } tmp_ar[i++] = cb.apply(obj, tmp); } else { tmp_ar[i++] = tmp; } tmp = []; } return tmp_ar; } {% endcodeblock %} - [Raw function on GitHub](https://github.com/kvz/phpjs/blob/master/functions/array/array_map.js) Please note that php.js uses JavaScript objects as substitutes for PHP arrays, they are the closest match to this hashtable-like data structure. Please also note that php.js offers community built functions and goes by the [McDonald's Theory](https://medium.com/what-i-learned-building/9216e1c9da7d). We'll put online functions that are far from perfect, in the hopes to spark better contributions. Do you have one? Then please just: - [Edit on GitHub](https://github.com/kvz/phpjs/edit/master/functions/array/array_map.js) ### Example 1 This code {% codeblock lang:js example %} array_map( function (a){return (a * a * a)}, [1, 2, 3, 4, 5] ); {% endcodeblock %} Should return {% codeblock lang:js returns %} [ 1, 8, 27, 64, 125 ] {% endcodeblock %} ### Other PHP functions in the array extension {% render_partial _includes/custom/array.html %}