phpjs
Version:
101 lines (84 loc) • 2.77 kB
Markdown
layout: page
title: "JavaScript array_pad function"
comments: true
sharing: true
footer: true
alias:
- /functions/view/array_pad:328
- /functions/view/array_pad
- /functions/view/328
- /functions/array_pad:328
- /functions/328
<!-- Generated by Rakefile:build -->
A JavaScript equivalent of PHP's array_pad
{% codeblock array/array_pad.js lang:js https://raw.github.com/kvz/phpjs/master/functions/array/array_pad.js raw on github %}
function array_pad (input, pad_size, pad_value) {
// From: http://phpjs.org/functions
// + original by: Waldo Malqui Silva
// * example 1: array_pad([ 7, 8, 9 ], 2, 'a');
// * returns 1: [ 7, 8, 9]
// * example 2: array_pad([ 7, 8, 9 ], 5, 'a');
// * returns 2: [ 7, 8, 9, 'a', 'a']
// * example 3: array_pad([ 7, 8, 9 ], 5, 2);
// * returns 3: [ 7, 8, 9, 2, 2]
// * example 4: array_pad([ 7, 8, 9 ], -5, 'a');
// * returns 4: [ 'a', 'a', 7, 8, 9 ]
var pad = [],
newArray = [],
newLength,
diff = 0,
i = 0;
if (Object.prototype.toString.call(input) === '[object Array]' && !isNaN(pad_size)) {
newLength = ((pad_size < 0) ? (pad_size * -1) : pad_size);
diff = newLength - input.length;
if (diff > 0) {
for (i = 0; i < diff; i++) {
newArray[i] = pad_value;
}
pad = ((pad_size < 0) ? newArray.concat(input) : input.concat(newArray));
} else {
pad = input;
}
}
return pad;
}
{% endcodeblock %}
- [Raw function on GitHub](https://github.com/kvz/phpjs/blob/master/functions/array/array_pad.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_pad.js)
### Example 1
This code
{% codeblock lang:js example %}
array_pad([ 7, 8, 9 ], 2, 'a');
{% endcodeblock %}
Should return
{% codeblock lang:js returns %}
[ 7, 8, 9]
{% endcodeblock %}
### Example 2
This code
{% codeblock lang:js example %}
array_pad([ 7, 8, 9 ], 5, 'a');
{% endcodeblock %}
Should return
{% codeblock lang:js returns %}
[ 7, 8, 9, 'a', 'a']
{% endcodeblock %}
### Example 3
This code
{% codeblock lang:js example %}
array_pad([ 7, 8, 9 ], 5, 2);
{% endcodeblock %}
Should return
{% codeblock lang:js returns %}
[ 7, 8, 9, 2, 2]
{% endcodeblock %}
### Other PHP functions in the array extension
{% render_partial _includes/custom/array.html %}