Ramda - Quick Tips #1

01/04/2022, Tue
Categories: #JavaScript
Tags: #ramda

Remove Falsey Values from an Array

Use without as a means to remove falsey values from your arrays. The first argument to the without method takes in an array which will represent the elements which are to be removed when found in the second argument array. You can include any values in the first argument array which you deem to be a "falsey" value.

R.without([false, null, ''], [false, null, '', 1, 2, null, 3, 4, false, 5]);

// Outputs
// [1, 2, 3, 4, 5]

Pattern Matching (Cond) / Compact If Statements Matching

From the official documentation cond example on the use of cond, this method can mimic the behavior of pattern matching by encapsulating multiple conditions into one function which you then pass in a value for comparison:

const fn = R.cond([
  [R.equals(0),   R.always('water freezes at 0°C')],
  [R.equals(100), R.always('water boils at 100°C')],
  [R.T,           temp => 'nothing special happens at ' + temp + '°C']
]);

fn(0);
// Outputs: 'water freezes at 0°C'

fn(50);
// Outputs: 'nothing special happens at 50°C'

fn(100);
// Outputs: 'water boils at 100°C'