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

How can I convert a complex if/ifelse/else condition to a readable Object Literal in JavaScript?

我重写了我的代码,以实现我认为我想要完成的目标。我无法用对象字面量代替 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)

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

这是 Either monad 的实际用例。不要让不熟悉的术语吓到你。在这里,我们以 lo-fi 的方式演示该技术,如 okerr。有问题就问-

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 return 有效密码,而不是将其记录到控制台。

可选择将 console.error 替换为 msg => { throw Error(msg) } 以使 validate 抛出与特定失败相对应的错误。