ramda.js中带有模板字符串的Pointfree-Style

时间:2018-08-08 07:18:20

标签: javascript functional-programming ramda.js pointfree

我在ramda.js中编写无点样式的函数时遇到问题,想知道是否有人可以帮助我。 getEnv函数读取一个env变量,如果找不到该变量,则记录到控制台。

这是我的代码

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'))

我想删除name函数的getEnv参数(如果可能的话,也可以放在env函数的参数上),但不知道如何执行此操作。

3 个答案:

答案 0 :(得分:1)

函数getEnv的作用超出应有的程度。实际上,它返回路径的内容 记录验证消息

将其拆分为两个单独的函数。在下面的示例中,我将其称为findPathvalidatePath,它们通常适用于所有路径。我已经将validatePath包装到另一个名为validateEnvPath的函数中,该函数直接搜索“ env”

要摆脱env,您可以执行以下操作:R.flip (R.curry (R.path))。这将使函数咖喱然后变为参数,因此您可以告诉函数您要首先查询的位置

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>

答案 1 :(得分:1)

考虑使用Either单子。 Sanctuary已实施,并与其兄弟 ramda 玩得很好:

const viewEnv = S.pipe ([
    S.flip (R.append) (['env']),
    R.lensPath,
    R.view,
    S.T (process),
    S.toEither ('Given variable could not be retrieved')
])

const log = R.tap (console.log)

const eitherSomeVar = viewEnv ('someVar')
const eitherWhatever = S.bimap (log) (doSomeOtherStuff)

答案 2 :(得分:0)

此外,还可以编写以下内容

const path = R.flip(R.path) // already curried

const findPathInProcess = R.pipe(
  path(process),
  R.when(
    R.isNil,
    R.always(undefined)
  )
)