-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
69 lines (54 loc) · 1.74 KB
/
index.js
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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
function snakeToCamelCase( obj ) {
if ( typeof obj === "string" ) {
return snakeToCamel( obj );
}
return traverse( obj, snakeToCamel );
}
function camelToSnakeCase( obj, options = { } ) {
if ( !isSimpleObject( options ) ) {
return obj; // avoiding String and other custom objects
}
if ( typeof obj === "string" ) {
return camelToSnake( obj, options );
}
return traverse( obj, camelToSnake, options );
}
module.exports = {
snakeToCamelCase,
camelToSnakeCase,
};
function traverse( obj, transform, options ) {
if ( !obj ) {
return obj;
}
if ( typeof obj !== "object" ) {
return obj; // must be an object
}
if ( isArray( obj ) ) {
return obj.map( el => traverse( el, transform, options ) );
}
if ( !isSimpleObject( obj ) ) {
return obj; // avoiding String and other custom objects
}
return Object.keys( obj ).reduce( ( acc, key ) => {
const convertedKey = transform( key, options );
acc[ convertedKey ] = traverse( obj[ key ], transform, options );
return acc;
}, { } );
}
function isArray( obj ) {
return Object.prototype.toString.call( obj ) === "[object Array]";
}
function isSimpleObject( obj ) {
return Object.prototype.toString.call( obj ) === "[object Object]";
}
function snakeToCamel( str ) {
return str.replace( /[_-](\w|$)/g, ( match, value ) => value.toUpperCase( ) );
}
function camelToSnake( str, { digitsAreUpperCase } ) {
const firstPass = str.replace( /[a-z][A-Z]/g, ( letters ) => `${ letters[ 0 ] }_${ letters[ 1 ].toLowerCase( ) }` );
if ( digitsAreUpperCase ) {
return firstPass.replace( /[0-9]/g, ( digit ) => `_${ digit }` );
}
return firstPass;
}