Skip to content

Instantly share code, notes, and snippets.

@mrcampbell
Created September 2, 2016 16:02
Show Gist options
  • Save mrcampbell/3a3fd056120f4db6836171be7b2edfff to your computer and use it in GitHub Desktop.
Save mrcampbell/3a3fd056120f4db6836171be7b2edfff to your computer and use it in GitHub Desktop.
Similar to SQL's NVL function, but with an optional condition to
// 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