UNPKG

2.06 kBJavaScriptView Raw
1// Convert square-bracket to dot notation.
2var toDotNotation = exports.toDotNotation = function (str) {
3 return str.replace(/\[((.)*?)\]/g, ".$1");
4};
5
6// Gets nested properties without throwing errors.
7var getProp = exports.getProp = function (property, obj) {
8 var levels = toDotNotation(property).split(".");
9
10 while (obj != null && levels[0]) {
11 obj = obj[levels.shift()];
12 if (obj == null) obj = "";
13 }
14
15 return obj;
16}
17
18// Sets nested properties.
19var setProp = exports.setProp = function (property, obj, value) {
20 var levels = toDotNotation(property).split(".");
21
22 while (levels[0]) {
23 var p = levels.shift();
24 if (typeof obj[p] !== "object") obj[p] = {};
25 if (!levels.length) obj[p] = value;
26 obj = obj[p];
27 }
28
29 return obj;
30}
31
32var clone = exports.clone = function (obj) {
33 // Untested, probably better:-> return Object.create(obj).__proto__;
34 return JSON.parse(JSON.stringify(obj));
35}
36
37/**
38 * camelize(str): -> String
39 * - str (String): The string to make camel-case.
40 *
41 * Converts dash-separated words into camelCase words. Cribbed from Prototype.js.
42 *
43 * field-name -> fieldName
44 * -field-name -> FieldName
45**/
46var camelize = exports.camelize = function (str) {
47 return (str || "").replace(/-+(.)?/g, function(match, chr) {
48 return chr ? chr.toUpperCase() : '';
49 });
50}
51
52/*
53 * Recursively merge properties of two objects
54 * http://stackoverflow.com/questions/171251/how-can-i-merge-properties-of-two-javascript-objects-dynamically/383245#383245
55 */
56var merge = exports.merge = function (obj1, obj2) {
57 for (var p in obj2) {
58 try {
59 // Property in destination object set; update its value.
60 if ( obj2[p].constructor==Object ) {
61 obj1[p] = merge(obj1[p], obj2[p]);
62 } else {
63 obj1[p] = obj2[p];
64 }
65 } catch (e) {
66 // Property in destination object not set; create it and set its value.
67 obj1[p] = obj2[p];
68 }
69 }
70 return obj1;
71}
72
73var hasValue = exports.hasValue = function (value) {
74 return !(undefined === value || null === value || "" === value);
75}
\No newline at end of file