How to use the cond function from ramda

Find comprehensive JavaScript ramda.cond code examples handpicked from public code repositorys.

ramda.cond is a function that allows you to define a set of conditions and corresponding functions to be executed based on the input value.

23
24
25
26
27
28
29
30
31
32
  R.adjust(0, getUserHeader),
  R.values,
  R.pick(['user', 'header'])
);

const coerceToArray = R.cond([
  [R.is(String), v => [v]],
  [R.isNil, R.always([])],
  [R.T, R.identity],
]);
fork icon303
star icon0
watch icon2

+ 3 other calls in file

4
5
6
7
8
9
10
11
12
13
14
const ttlFromExpiry = R.compose(
  R.min(GCM_MAX_TTL),
  (expiry) => expiry - Math.floor(Date.now() / 1000)
);


const extractTimeToLive = R.cond([
  [R.propIs(Number, 'expiry'), ({ expiry }) => ttlFromExpiry(expiry)],
  [R.propIs(Number, 'timeToLive'), R.prop('timeToLive')],
  [R.T, R.always(DEFAULT_TTL)],
]);
fork icon117
star icon518
watch icon0

How does ramda.cond work?

ramda.cond is a function in the Ramda library that takes a list of predicate-function pairs, evaluates each predicate function in turn on the provided argument(s), and returns the result of the first predicate that is truthy, along with the corresponding function applied to the arguments. If no predicate returns a truthy value, undefined is returned.

150
151
152
153
154
155
156
157
158
159
160
  if (cat === 'B' || cat === 'C') return cat
  return '!'
}


// R.cond is like a switch statement
const calculateNextReviewDate = R.cond([
  [R.equals('6'), () => moment().add(6, 'months').format('DD/MM/YYYY')],
  [R.equals('12'), () => moment().add(1, 'years').format('DD/MM/YYYY')],
  [R.T, R.always('')],
])
fork icon3
star icon4
watch icon0

22
23
24
25
26
27
28
29
30
31
32
33
34


const generateValidationSet = (data, rules) => R.compose(R.flatten, mapValueAndRules)(data, rules);


const validationError = (errors) => Result.Error(new ApiError(errors, 'Validation Error', HTTP_CONSTANT.BAD_REQUEST));


const formResult = (errors) => R.cond([
	[R.isEmpty, Result.Ok],
	[R.T, validationError]
])(errors);

fork icon4
star icon2
watch icon2

+ 275 other calls in file

Ai Example

1
2
3
4
5
6
7
8
9
10
11
12
const { cond, equals, T, always } = require("ramda");

const gradeFunc = cond([
  [equals(100), always("A+")],
  [equals(90), always("A")],
  [equals(80), always("B")],
  [equals(70), always("C")],
  [equals(60), always("D")],
  [T, always("F")],
]);

console.log(gradeFunc(95)); // Output: A

In this example, we define a function gradeFunc using ramda.cond, which takes a numeric grade and returns a letter grade based on some conditions. The cond function takes an array of pairs where the first element is a predicate function and the second element is a function that should be executed if the predicate function returns true. The T function is a Ramda utility function that always returns true and can be used as a catch-all predicate function. In this example, the equals function is used to check whether the grade matches a certain value and the always function is used to return a constant string for that grade. Finally, the gradeFunc function is called with a grade of 95, which matches the second predicate function, and returns the letter grade 'A'.

21
22
23
24
25
26
27
28
29
30
31
32
console.log('alwaysTrue=', alwaysTrue())
console.log('alwaysTrue=', alwaysTrue(1))
console.log('alwaysTrue=', alwaysTrue(1, 'Two'))




const fn = _.cond([
    [_.equals(0), _.always('water freezes at 0°C')],
    [_.equals(100), _.always('water boils at 100°C')],
    [_.T, temp => 'nothing special happens at ' + temp + '°C']
])
fork icon1
star icon2
watch icon0

616
617
618
619
620
621
622
623
624
625
626
627
const iAndroid = R.includes(R.__, androidPlatforms);


const withFallback = (obj, platform) => obj[platform] || obj["default"];


function createManifest({ version, platform }) {
  const basePlatform = R.cond([
    [isApple, R.always("apple")],
    [iAndroid, R.always("android")],
  ])(platform);

fork icon0
star icon3
watch icon0

16
17
18
19
20
21
22
23
24
25
26
27
} = require('../a11y.config.js');


const STORYBOOK_BUILD_DIR = path.resolve(__dirname, '../', storybookBuildDir);
const STORYBOOK_IFRAME = path.join(STORYBOOK_BUILD_DIR, 'iframe.html');


const severityToColor = R.cond([
  [R.equals('error'), R.always('red')],
  [R.equals('warning'), R.always('yellow')],
  [R.equals('notice'), R.always('blue')],
]);
fork icon0
star icon2
watch icon0

6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
* @sig [[(*... -> Boolean),(*... -> *)]] -> (*... -> *)
* @param {Array} pairs
* @return {Function}
* @example
*
*      var 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']
*      ]);
fork icon0
star icon0
watch icon0

+ 18 other calls in file

97
98
99
100
101
102
103
104
105
106
107
108
Action.allow = R.always({action: 'allow'});
Action.reveal = role => ({action: 'reveal', role});


Action.typeEq = R.curry((a, b) => a.action == b.action);


Action.listAvailable = R.cond([
  [State.eq(State.START_OF_TURN), game => [
    Action.tax(),
    Action.income(),
  ]],
fork icon0
star icon0
watch icon0

+ 7 other calls in file

3
4
5
6
7
8
9
10
11
12
13
14
const content = R.split('\n', fs.readFileSync(`${__dirname}/input.txt`, {encoding: 'utf-8'}))


const lastLens = R.lens(a => a[R.dec(R.length(a))],
  R.curry((v, a) => R.set(R.lensIndex(R.dec(R.length(a))), v, a)));


const directionToVector = R.cond([
  [R.equals('U'), R.always([0, 1])],
  [R.equals('D'), R.always([0, -1])],
  [R.equals('L'), R.always([-1, 0])],
  [R.equals('R'), R.always([1, 0])],
fork icon0
star icon0
watch icon0

1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
* @param {Array} pairs A list of [predicate, transformer]
* @return {Function}
* @see R.ifElse, R.unless, R.when
* @example
*
*      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']
*      ]);
fork icon0
star icon0
watch icon2

+ 3 other calls in file

2
3
4
5
6
7
8
9
10
11
12
13


const subjectOrBody = either(prop('subject'), prop('body'))


const fromCond = (dispatchTable, key, otherwise) =>
    new Promise((resolve, reject) => {
        cond([
            [has(key), pipe(prop(key), resolve)],
            [has('default'), pipe(prop('default'), resolve)],
            [T, pipe(always(otherwise), reject)],
        ])(dispatchTable)
fork icon0
star icon0
watch icon0

40
41
42
43
44
45
46
47
48
49
50
  // isStop: targetNode.isStop,
  ...targetNode
})
console.log(res);


const judgeWaterState = R.cond([
  [R.lte(R.__,0), R.always('water freezes as 0°C')],
  [R.gte(R.__,100), R.always('water boils at 100°C')],
  [R.T, temp => `nothing special at ${temp}°C`],
])
fork icon0
star icon0
watch icon0

21
22
23
24
25
26
27
28
29
30
31
32
33
});




const generateValidationSet = (data, rules) => R.compose(R.flatten, mapValueAndRules)(data, rules);


const formResult = errors => R.cond([
    [R.isEmpty, Result.Ok],
    [R.T, validationError]
])(errors);

fork icon0
star icon0
watch icon0

164
165
166
167
168
169
170
171
172
173
174
      R.propEq('revealed', false),
      R.propEq('role', role)))
  ))
};


Game.applyAction = R.cond([
  [Game.actionEq('income'), R.over(activePlayerLens, Player.adjustCash(1))],
  [Game.actionEq('foreign-aid'), R.over(activePlayerLens, Player.adjustCash(2))],
  [Game.actionEq('tax'), R.over(activePlayerLens, Player.adjustCash(3))],
  [Game.actionEq('assassinate'), Game.applyRevealAction],
fork icon0
star icon0
watch icon0

+ 6 other calls in file

Other functions in ramda

Sorted by popularity

function icon

ramda.clone is the most popular function in ramda (30311 examples)