1.3.1 • Published 3 months ago

kotlin-when v1.3.1

Weekly downloads
-
License
ISC
Repository
github
Last release
3 months ago

kotlin-when

This is a small implementation to mock the when functionality that is provided by kotlin. In this library, if a matching case is found, only the code in the respective case block is executed, and execution continues with the next statement after the when block.

This essentially means that we don’t need break statements at the end of each case block.

Installation

npm install kotlin-when

Usage

String matching

when(dayOfTheWeek, {
  "Monday": () => console.log("It's a Monday",)
  'Tuesday': () => console.log( "It's a Tuesday")
}); // outputs "Bingo! It's eleven."

Number matching

when(12, {
  "cat": () => "Cat really?",
  12: (identifier) => String(identifier),
}); // ouputs "12"

Multiple conditions on one line

If we want to run the same function for multiple conditions then we are able to do so by passing a comma separated string of the possible values this is similar to stacking cases in switch.

when('2', {
  '11': () => "Bingo! It's eleven.",
  "1,2,3": () => "Multi condition value",
}); // outputs "Multi condition value"

Default cases

Sometimes we may not find the value and have to fallback on an else value to use this feature pass an else keyword and a function.

when('three', {
  '11': () => "Bingo! It's eleven.",
  else: () => 'Else value',
});

Nested whens

Sure why not

when('11', {
  '11': (identifier) => when(identifier, {
    '11': () => 'Nested'
  }),
})

Checking with conditions

In order to check boolean conditions we need to first omit the condition value and pass our object as the first argument, then we need to pass true as the second value in order to enable conditional comparisons. We must wrap each key with square brackets and wrap the conditions in a String() declaration to convert it to be usable in our code

when({
  [String('11' === '11')]: () => "true value",
  [String('12' === '11')]: () => "false value",
}, true)
1.3.1

3 months ago

1.2.3

7 months ago

1.2.2

7 months ago

1.2.1

7 months ago

1.2.0

7 months ago

1.1.3

7 months ago

1.1.2

7 months ago

1.1.1

7 months ago

1.1.0

7 months ago

1.0.0

7 months ago