getDeepVal QUnit
by Victor
HTML
<link rel="stylesheet" href="http://code.jquery.com/qunit/qunit-1.12.0.css">
<script src="http://code.jquery.com/qunit/qunit-1.12.0.js"></script>
<div id="qunit"></div>
<div id="qunit-fixture"></div>
JavaScript
function getDeepVal(object, path, defaultValue) {
if (typeof object === 'undefined' || object === null) return defaultValue;
const pathArray = path.split(/\.|\[["']?|["']?\]/);
for (let i = 0, l = pathArray.length; i < l; i++) {
if (pathArray[i] === '') continue;
object = object[pathArray[i]];
if (typeof object === 'undefined' || object === null) return defaultValue;
}
return (typeof object === 'undefined' || object === null) ? defaultValue : object;
}
var emptyArray = [];
var array = [
1, //0
"Lorem Ipsum", //1
{}, //2
{
foo: 1
}, //3
null, //4
NaN, //5
Infinity, //6
-Infinity, //7
+Infinity, //8
true, //9
false, //10
undefined, //11
function() {}, //12
3.14, //13
1 / 1.5, //14
];
var emptyObj = {};
var obj = {
_null: null,
foo: 1,
bar: {
baz: 1,
str: "Lorem ipsum"
},
d1: {
d2: {
d3: {
d4: {
d5: {
d6: {
d7: {
d8: {
d9: {
d10: "you reached the top!"
}
}
}
}
}
}
}
}
},
arr: [1, 2, 3],
matrix2d: [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
],
o: {
1: [{
foo: [1, 2]
}, {
bar: [3, 4]
}]
}
};
var _number = 1;
var _true = true;
var _false = false;
var _string = "hello";
var _emptyString = "";
var _undefined = void 0;
var _null = null;
var _nan = NaN;
test("Empty obj empty path", function() {
ok(getDeepVal(emptyObj, "") === emptyObj);
});
test("obj.invalidKey", function() {
ok(getDeepVal(obj, "invalidKey") ===...