View: array_reverse

Function:
Description: Return input as a new array with the order of the entries reversed.
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
34
35
36
37
38
39
40
function array_reverse (array, preserve_keys) {
    // http://jsphp.co/jsphp/fn/view/array_reverse
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Karol Kowalski
    // *     example 1: array_reverse( [ 'php', '4.0', ['green', 'red'] ], true);
    // *     returns 1: { 2: ['green', 'red'], 1: 4, 0: 'php'}
    var isArray = Object.prototype.toString.call(array) === "[object Array]",
        tmp_arr = preserve_keys ? {} : [],
        key;
        
    if (isArray && !preserve_keys) {
        return array.slice(0).reverse();
    }

    if (preserve_keys) {
        var keys = [];
        for (key in array) {
            // if (array.hasOwnProperty(key)) {
            keys.push(key);
            // }
        }
        
        var i = keys.length;
        while (i--) {
            key = keys[i];
            // FIXME: don't rely on browsers keeping keys in insertion order
            // it's implementation specific
            // eg. the result will differ from expected in Google Chrome
            tmp_arr[key] = array[key];
        }
    } else {
        for (key in array) {
            // if (array.hasOwnProperty(key)) {
            tmp_arr.unshift(array[key]);
            // }
        }
    }

    return tmp_arr;
}
Comment on array_reverse version 34
Tests
Benchmark
[top]

Comments

There are no comments yet, be the first!

Please Login or Register to post comments.