Home > Software design >  Ramda.when always return true using fs
Ramda.when always return true using fs

Time:12-15

I am trying to use Ramda.when to execute only if a condition is true but it's always returning true:

const bla2 = path => () => R.when(fs.existsSync(path()), console.log(path()))

Is there anyway to use Ramda.when with fs.existsSync?

edit:

Even set false this is not working:

const bla3 => () => R.when(false, console.log('bla'))

This is the real code:

const moveEnvironmentVarsFile = (oldPath, newPath) => () => R.when(fs.existsSync(oldPath()), fs.renameSync(oldPath(), newPath())) 

CodePudding user response:

I don't think R.when is appropriate for what you're trying to do. R.when's purpose is to transform a value, but only if that value matches a condition. It expects you to pass in three things:

  1. A function which checks the condition
  2. A function which does the transformation
  3. A value that you want to send through this process

fs.existsSync can conceivably be used as argument 1, such as the following contrived example which appends "exists" to a string if the file exists:

const result = R.when(
  fs.existsSync,
  (val) => val   "exists",
  "some/file"
);
// result is either some/file or some/fileexists

In real word, I am trying to rename a file using fs. How can I do it using ramda or any functional way in JS?

Honestly, i would just use an if/else and not use Ramda:

const myFunc = (filename) => {
  if (fs.existsSync(filename) {
    // do something
  } else {
    // do something else
  }
}

If you really want to use ramda to create that code for you, you could use R.ifElse:

const myFunc = R.ifElse(
  fs.existsSync,
  (filename) => { /* do something */ },
  (filename) => { /* do someething else */ }
);
  • Related