UNPKG

1.61 kBJavaScriptView Raw
1/*
2 * grunt
3 * https://github.com/cowboy/grunt
4 *
5 * Copyright (c) 2012 "Cowboy" Ben Alman
6 * Licensed under the MIT license.
7 * http://benalman.com/about/license/
8 */
9
10(function(exports) {
11
12 // Split strings on dot, but only if dot isn't preceded by a backslash. Since
13 // JavaScript doesn't support lookbehinds, use a placeholder for "\.", split
14 // on dot, then replace the placeholder character with a dot.
15 function getParts(str) {
16 return str.replace(/\\\./g, '\uffff').split('.').map(function(s) {
17 return s.replace(/\uffff/g, '.');
18 });
19 }
20
21 // Get the value of a deeply-nested property exist in an object.
22 exports.get = function(obj, parts, create) {
23 if (typeof parts === 'string') {
24 parts = getParts(parts);
25 }
26
27 var part;
28 while (typeof obj === 'object' && obj && parts.length) {
29 part = parts.shift();
30 if (!(part in obj) && create) {
31 obj[part] = {};
32 }
33 obj = obj[part];
34 }
35
36 return obj;
37 };
38
39 // Set a deeply-nested property in an object, creating intermediary objects
40 // as we go.
41 exports.set = function(obj, parts, value) {
42 parts = getParts(parts);
43
44 var prop = parts.pop();
45 obj = exports.get(obj, parts, true);
46 if (obj && typeof obj === 'object') {
47 return (obj[prop] = value);
48 }
49 };
50
51 // Does a deeply-nested property exist in an object?
52 exports.exists = function(obj, parts) {
53 parts = getParts(parts);
54
55 var prop = parts.pop();
56 obj = exports.get(obj, parts);
57
58 return typeof obj === 'object' && obj && prop in obj;
59 };
60
61}(typeof exports === 'object' && exports || this));