如何将复杂的 if/ifelse/else 条件转换为 JavaScript 中可读的对象文字?

问题描述 投票:0回答:2

我将代码重写为我认为我想要完成的目标。 我无法使用对象文字作为 if/else 或 switch 的替代品。 您如何将 if/else 条件转换为下面的对象文字?

let bobRes = "A123";
//stored password in database
let sPass = "A1234";
let qState = "q1";

function responseHandler(bobResValue, sPassValue, qStateValue) {
  if (sPass === "" && qStateValue === "q1") {

    return "Create a new password using five digits.";
  } else if (bobResValue.length !== 5 && qStateValue === "q1") {

    return "Password is too short!";
  } else if (bobResValue !== sPassValue) {

    return "Wrong Password";
  } else if (bobResValue === sPass) {

    return "Correct Password";
  } else {

    return "You must enter a password to continue?";
  }
}

let finalResponse = responseHandler(bobRes, sPass, qState);
console.log(finalResponse)

我尝试转换为对象文字! 但我被逻辑困住了......

let bobRes = "A123";
//stored password in database
let sPass = "A1234";
 


function responseHandler(bobResValue) {
  let respObj = {

    "None": "You must enter a password." 
   
  }
  let respObj2 = {
      passWordLength: (bobResValue) => bobResValue.length != 5,
  }

let respObj3 = {
      passWordLength: (bobResValue) => bobResValue === 5,
  }

  respObj[bobResValue] ?? respObj2[passWordLength]?? "You must enter a password to continue!";
}

let finalResponse = responseHandler(bobRes, sPass, qState);
console.log(finalResponse)

javascript ecmascript-6
2个回答
1
投票

不要放弃!这些类型的重构将教您识别如何思考程序的问题并永久解锁新技术。

这是

Either
monad 的实际用例。不要让不熟悉的术语吓到您。在这里,我们以低保真方式演示该技术,如
ok
err
。如果您有任何疑问,请询问 -

const ok = value => ({
  chain: f => f(value),
  get: (ifOk, _) => ifOk(value)
})

const err = value => ({
  chain: _ => err(value),
  get: (_, ifErr) => ifErr(value)
})

const isEmpty = s => (s === "")
  ? err("create a new password using five digits")
  : ok(s)

const isTooShort = s => (s.length != 5 || Number.isNaN(Number.parseInt(s)))
  ? err("password is not five digits")
  : ok(s)

const isMatch = match => s => (s !== match)
  ? err("wrong password")
  : ok(s)

function validate(pass, match) {
  return isEmpty(pass)
    .chain(isTooShort)
    .chain(isMatch(match))
    .get(console.log, console.error)
}

validate("", "foo")
validate("123", "123")
validate("12345", "9876")
validate("12345", "12345")

console.log
替换为身份函数
v => v
,让
validate
返回有效密码,而不是将其记录到控制台。

可以选择将

console.error
替换为
msg => { throw Error(msg) }
,以使
validate
抛出与特定故障相对应的错误。


0
投票

Chanyanut SawasdeePop.F4/689=64:45-4476=6789.34,79% cer7, xse907, vrr35, cwad,3 ceu,467 xest.7, fgji890, zsd6800-6300=500.:137/537?=&4685'489在此处输入图像描述 9กุมภาพันธ์2539ปีชวด28年จังหวัดสมุทรสงคราม75000

© www.soinside.com 2019 - 2024. All rights reserved.