Optional chaining

Benchmark created on


Setup

function digKeyPath(obj, path, def = digKeyPath.NOT_FOUND){
    if(path.split) path = path.split('.');
    for(let i=0, len = path.length; i<len; ++i){
        if(obj) obj = obj[path[i]];
        else return def;
    }
    return obj == void 0 ? def : obj;
}

var obj = {
	undef: undefined,
	zero: 0,
	one: 1,
	n: null,
	f: false,
    t:[2,2],
	a: {
		two: 2,
		b: {
			three: 3,
			c: {
				four: 4
			}
		}
	}
};

Test runner

Ready to run.

Testing in
TestOps/sec
dlv (modified) string
digKeyPath(obj,"undef")
    digKeyPath(obj,"zero.a.b.c")
    digKeyPath(obj,"t.a")
    digKeyPath(obj,"a.b.c.four")
ready
Optional chaining
obj?.undef
obj?.zero?.a?.b?.c
obj?.t?.a
obj?.a?.b?.c?.four
ready
dlv (modified) array

    digKeyPath(obj,["undef"])
    digKeyPath(obj,["zero","a","b","c"])
    digKeyPath(obj,["t","a"])
    digKeyPath(obj,["a","b","c","four"])
ready

Revisions

You can edit these tests or add more tests to this page by appending /edit to the URL.