# all files / keystone/lib/ path.js

92.86% Statements 39/42
86.36% Branches 19/22
100% Functions 4/4
97.44% Lines 38/39

    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
    681×

    1×

    109×

    109×
    109×
    109×

    109×
    2×
    2×
    6×
    4×

    6×

    2×
    2×

    109×
    848×
    848×
    848×
    331×
    331×
    331×
    61×

    270×
    89×
    89×

    270×
    79×

    191×

    270×
    517×
    383×

    134×
    188×
    171×

    117×

    109×
    100×

    109×

     var utils = require('keystone-utils');

    /**
     * Path Class
     *
     * @api public
     */

    module.exports = function Path (str) {

    	Iif (!(this instanceof Path)) {
    		return new Path(str);
    	}

    	var parts = this.parts = str.split('.');
    	var last = this.parts[this.parts.length - 1];
    	var withoutLast = str.substr(0, str.length - last.length - 1);

    	this.addTo = function (obj, val) {
    		var o = obj;
    		for (var i = 0; i < parts.length - 1; i++) {
    			if (!utils.isObject(o[parts[i]])) {
    				o[parts[i]] = {};
    			}
    			o = o[parts[i]];
    		}
    		o[last] = val;
    		return obj;
    	};

    	this.get = function (obj, subpath) {
    		Iif (typeof obj !== 'object') throw new TypeError('Path.get: obj argument must be an Object');
    		var i;
    		if (subpath) {
    			var nested = subpath.charAt(0) === '.';
    			var flatPath = str + subpath;
    			if (flatPath in obj) {
    				return obj[flatPath];
    			}
    			for (i = 0; i < parts.length - (nested ? 0 : 1); i++) {
    				Iif (typeof obj !== 'object') return undefined;
    				obj = obj[parts[i]];
    			}
    			if (nested) {
    				subpath = subpath.substr(1);
    			} else {
    				subpath = last + subpath;
    			}
    			return (typeof obj === 'object') ? obj[subpath] : undefined;
    		} else if (str in obj) {
    			return obj[str];
    		} else {
    			for (i = 0; i < parts.length; i++) {
    				if (typeof obj !== 'object') return undefined;
    				obj = obj[parts[i]];
    			}
    			return obj;
    		}
    	};

    	this.append = function (append) {
    		return str + append;
    	};

    	return this;

    };