Created
September 2, 2016 16:02
-
-
Save mrcampbell/3a3fd056120f4db6836171be7b2edfff to your computer and use it in GitHub Desktop.
Similar to SQL's NVL function, but with an optional condition to
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// null value logic - condition provided | |
function nvlc(input, alternative, condition=null) { | |
"use strict"; | |
if (condition != null) { | |
if (condition(input)) { | |
return input; | |
} else { | |
return alternative; | |
} | |
} else { | |
if (input === null) { | |
return alternative | |
} else { | |
return input; | |
} | |
} | |
} | |
console.log(nvlc(-3, 5, (i) => {i > 0})); // returns 5 | |
console.log(nvlc([], [0], (i) => {i.length > 0})); // returns [ 0 ] | |
console.log(nvlc(null, 3)); // returns 3 | |
console.log(nvlc(42, 5)); // returns 42 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment