Skip to content

Commit

Permalink
feat(general): optionalChaining utility
Browse files Browse the repository at this point in the history
  • Loading branch information
medikoo committed Aug 2, 2017
1 parent 3e42dd4 commit 26332b5
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 0 deletions.
12 changes: 12 additions & 0 deletions optional-chaining.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
"use strict";

var isValue = require("./object/is-value");

var slice = Array.prototype.slice;

// eslint-disable-next-line no-unused-vars
module.exports = function (value, propertyName1 /*, …propertyNamen*/) {
var propertyNames = slice.call(arguments, 1), index = 0, length = propertyNames.length;
while (isValue(value) && index < length) value = value[propertyNames[index++]];
return index === length ? value : undefined;
};
17 changes: 17 additions & 0 deletions test/optional-chaining.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
"use strict";

module.exports = function (t, a) {
var obj = { foo: { bar: "elo", par: null } };
a(t(), undefined);
a(t(null), null);
a(t(obj), obj);
a(t(obj, "foo"), obj.foo);
a(t(obj, "foo", "bar"), "elo");
a(t(obj, "foo", "bar", "slice"), String.prototype.slice);
a(t(obj, "foo", "par"), null);
a(t(obj, "foo", "par", "marko"), undefined);
a(t(obj, "marko"), undefined);
a(t(""), "");
a(t("", "foo"), undefined);
a(t("", "slice"), String.prototype.slice);
};

0 comments on commit 26332b5

Please sign in to comment.