Search code examples
javascriptfunctional-programmingramda.jspointfree

Pointfree-Style with template-string in ramda.js


I've problems writing a pointfree-style function in ramda.js and wondered if anybody can help me with that. The getEnv function reads an env-variable and logs to console if it couldn't be found.

Here is my code

const env = name => R.path(['env', name], process);

const getEnv = name => R.pipe(
  env,
  R.when(R.isNil, () => log(`Missing env "${name}"`))
)(name);

console.log(getEnv('myenv'))

I'd want to drop the name parameter of the getEnv function (and if possible also on the env function) but don't know how to do this.


Solution

  • The function getEnv does more than it should. It actualy returns the content of the path or logs a validation message.

    Split it into two separate functions. In my example below, I call it findPath andvalidatePath, which works generically for all paths. I've wrapped validatePath into another function calledvalidateEnvPath, which searches directly for "env"

    To get rid of env you can do the following: R.flip (R.curry (R.path)). This will turn the function curry and then the arguments around, so you can tell the function where you want to query first

    const process = {env: {myenv: ':)'}}
    
    const path = R.flip(R.curry(R.path))
    
    const findPathInProcess = R.pipe(
      path (process),
      R.ifElse(
        R.isNil,
        R.always(undefined),
        R.identity
      )
    )
    
    const validatePath = path =>
      validationPathResponse (findPathInProcess( path )) (`can't find something under [${path}]`) 
    
    const validateEnvPath = path => 
      validatePath (buildPath (['env']) (path))
      
    const buildPath = xs => x =>
      xs.concat(x)
      
    const validationPathResponse = response => errorMessage =>
      response
        ? response
        : errorMessage
    
    
    console.log(validatePath(['env', 'myenv']))
    console.log(validateEnvPath('myenv'))
    console.log(validateEnvPath('yourenv'))
    <script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.25.0/ramda.min.js"></script>