Ifx?
ifx is a JavaScript module that provides "if-expression" to return a value. It can be alternative to ternary operator.
Motivation
Use of ternary operators to express stateless values and functions tends to result in significantly diminished readability when applied to complicated nesting conditions or multiple conditions.
I wanted to use conditional branches built on JavaScript which return values in the same manner as the if-expression in Scala to ensure readability in such situation.
Usage
- install
npm install ifx
- import
const If = require('ifx');
- ES6 syntax (recommend)
// stateless and readable to use ES6 arrow functionconst x = 1 2;console;
- formatted
// can be return valueconst fn = value Object ; console; // [ 5, 10, 15, 20, 25 ]console; // [ 'a', 'b', 'c' ]console; // []
- ES5 syntax
var If = ; var x = { return 1 } { return 2 } ; console; // 2
API
If = condition -> expected function -> object
If
is a curried function.- returned-object has methods
Else/ElseIF/Get
// every type can be returning valueconsole; // trueconsole; // aconsole; // nullconsole; // undefinedconsole; // [ 1 ]console; // {} // returned function apply to function onlytry 1 catche console // [Error: If() con be applied to a function only]
.Get = () -> value
- if you don't use
Else
,Get
gets rerutning a value.
// If(true)console; // 1 // If(false)console; // null
.Else = function -> value`
- When you use
Else
,Get
is unnecessary.
// If + Elseconsole; // 2
.ElseIf = condition -> expected function -> object
- Chain
ElseIf
, if you need conditions more than once.
// If + ElseIf + Getconsole; // 2console; // 3 // If + ElseIf + Elseconsole; // 4 // need conditiontry 1 2 catche console // [Error: ElseIf connot be applied to an empty value]
TypeScript Import
import * as If from 'ifx';
about specs
- It returns first matched value when conditions match more than once.
console; // 1console; // 3
- It returns null when all conditions don't match.
console; // nullconsole; // null
Author
jshosomichi
License
under the MIT license.