dlv
dlv copied to clipboard
Shaving some bytes with reduce
Hi there! By using an array reduce on the key, you'll can go even leaner with 124 bytes 💪
Unfortunately, after minification, using reduce is actually larger (using https://jscompress.com/ which uses UglifyJS 3 and Babili):
original (119 bytes):
export default function dlv(a,b,c,d){for(d=0,b=b.split?b.split('.'):b;a&&d<b.length;)a=a[b[d++]];return a===void 0?c:a}
with reduce (123 bytes):
export default function dlv(a,b,c){return(a=(b.split?b.split('.'):b).reduce(function(d,e){return d&&d[e]},a))===void 0?c:a}
Thanks for the great explanation @kevlened! This also jives with my experience. Worth noting that performance is also at play here, and reduce() has fairly poor performance.