View: array_pad

Function:
Description: Returns a copy of input array padded with pad_value to size pad_size.
Code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
function array_pad (input, pad_size, pad_value) {
    // http://jsphp.co/jsphp/fn/view/array_pad
    // +   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;
}
Comment on array_pad version 26
Tests
Benchmark
[top]

Comments

There are no comments yet, be the first!

Please Login or Register to post comments.