View: array_change_key_case

Function:
Description: Retuns an array with all string keys lowercased [or uppercased].
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
function array_change_key_case (array, cs) {
    // http://jsphp.co/jsphp/fn/view/array_change_key_case
    // +   original by: Ates Goral (http://magnetiq.com)
    // +   improved by: marrtins
    // +      improved by: Brett Zamir (http://brett-zamir.me)
    // *     example 1: array_change_key_case(42);
    // *     returns 1: false
    // *     example 2: array_change_key_case([ 3, 5 ]);
    // *     returns 2: {0: 3, 1: 5}
    // *     example 3: array_change_key_case({ FuBaR: 42 });
    // *     returns 3: {"fubar": 42}
    // *     example 4: array_change_key_case({ FuBaR: 42 }, 'CASE_LOWER');
    // *     returns 4: {"fubar": 42}
    // *     example 5: array_change_key_case({ FuBaR: 42 }, 'CASE_UPPER');
    // *     returns 5: {"FUBAR": 42}
    // *     example 6: array_change_key_case({ FuBaR: 42 }, 2);
    // *     returns 6: {"FUBAR": 42}
    var case_fn, key, tmp_ar = {};

    if (Object.prototype.toString.call(array) === '[object Array]') {
        return array;
    }
    if (array && typeof array === 'object' && array.change_key_case) { // Duck-type check for our own array()-created PHPJS_Array
        return array.change_key_case(cs);
    }
    if (array && typeof array === 'object' ) {
        case_fn = (!cs || cs === 'CASE_LOWER') ? 'toLowerCase' : 'toUpperCase';
        for (key in array) {
            tmp_ar[key[case_fn]()] = array[key];
        }
        return tmp_ar;
    }
    return false;
}
Comment on array_change_key_case version 2
Tests
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
function array_change_key_case_tests() {

  // API reference: http://docs.jquery.com/QUnit
  module( "array_change_key_case" );

  test( "array_change_key_case", function() {

    deepEqual( array_change_key_case( 42 ), false );
    deepEqual( array_change_key_case( [ 3, 5 ] ), [ 3, 5 ] );
    deepEqual( array_change_key_case( { FuBaR: 42 } ), { fubar: 42 } );
    deepEqual( array_change_key_case( { FuBaR: 42 }, 'CASE_LOWER' ), { fubar: 42 } );
    deepEqual( array_change_key_case( { FuBaR: 42 }, 'CASE_UPPER' ), { FUBAR: 42 } );
    deepEqual( array_change_key_case( { FuBaR: 42 }, 2 ), { FUBAR: 42 } );

  } );

}
Comment on array_change_key_case version 26 tests
Benchmark
[top]

Comments

There are no comments yet, be the first!

Please Login or Register to post comments.