repl.it
@rodrigorhas/

oif program

JavaScript

No description

fork
loading
main.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
/*
 * @name oif function
 * @description Options if function with fallback value and error handler
 */
const oif = (options, value, fallbackValue = null, errorFn = () => null) =>
  options[value] || options[fallbackValue] || errorFn();

const animals = {
  dog: "LOVELY",
  cat: "CUTE"
}

const throwError = (message) => new Error(message);

const oifResult = oif(animals, 'apple', 'cast', () => {
  console.error('option not found')
  return 'my_custom_fallback_value';
}) // my_custom_fallback_value

const oifResult2 = oif(animals, 'apple', 'cat') // CUTE
const oifResult3 = oif(animals, 'ball', 'gear', throwError) // Error...

/*
 * Uncomment to see all tests
 */

// console.log(oifResult)
// console.log(oifResult2)
// console.log(oifResult3)
Native Browser JavaScript
?