首页 > 解决方案 > 如何在这个javascript代码中添加“IF result = X”而不是“RETURN x”?

问题描述

我的代码:

const crypto = require('crypto');

const crashHash = '';
// Hash from bitcoin block #610546. Public seed event: https://twitter.com/Roobet/status/1211800855223123968
const salt = '0000000000000000000fa3b65e43e4240d71762a5bf397d5304b2596d116859c';

function saltHash(hash) {
 return crypto
  .createHmac('sha256', hash)
  .update(salt)
  .digest('hex');
}

function generateHash(seed) {
 return crypto
  .createHash('sha256')
  .update(seed)
  .digest('hex');
}

function divisible(hash, mod) {
 // We will read in 4 hex at a time, but the first chunk might be a bit smaller
 // So ABCDEFGHIJ should be chunked like  AB CDEF GHIJ
 var val = 0;

 var o = hash.length % 4;
 for (var i = o > 0 ? o - 4 : 0; i < hash.length; i += 4) {
  val = ((val << 16) + parseInt(hash.substring(i, i + 4), 16)) % mod;
 }

 return val === 0;
}

function crashPointFromHash(serverSeed) {
 const hash = crypto
  .createHmac('sha256', serverSeed)
  .update(salt)
  .digest('hex');

 const hs = parseInt(100 / 4);
 if (divisible(hash, hs)) {
  return 1;
 }

 const h = parseInt(hash.slice(0, 52 / 4), 16);
 const e = Math.pow(2, 52);

 return Math.floor((100 * e - h) / (e - h)) / 100.0;
}

function getPreviousGames() {
 const previousGames = [];
 let gameHash = generateHash(crashHash);

 for (let i = 0; i < 100; i++) {
  const gameResult = crashPointFromHash(gameHash);
  previousGames.push({ gameHash, gameResult });
  gameHash = generateHash(gameHash);
 }

 return previousGames;
}

function verifyCrash() {
 const gameResult = crashPointFromHash(crashHash);
 const previousHundredGames = getPreviousGames();

 return { gameResult, previousHundredGames };
}

console.log(verifyCrash());

代码沙箱


我试图让这段代码显示它已经显示的结果,但我希望它在每个gameResult数据的末尾添加一些东西,所以它看起来像这样:gameResult: 4.39 "maybe"

我试图在没有运气的情况下将这样的东西添加到代码中。我让它工作到它只会返回第一个gameResult而不是后面的那个的地步。如果有人可以提供帮助,那就太好了,或者如果您有我尝试使用的下面这段代码以外的其他方法,那也可以。

function gameResult
  const result =
    if (gameResult === 1) {
      return "no";
    };
    if (gameResult <= 3) {
      return "maybe";
    };
    if (gameResult <= 10) {
      return "yes";
    };

标签: javascriptnode.js

解决方案


所以,如果我理解正确,预期的输出应该是这样的,

{
    "gameResult": "4.39 "yes"",
    "previousHundredGames": [...]
}

我可以通过修改verifyCrash函数来做到这一点,

function verifyCrash() {
  let gameResult = crashPointFromHash(crashHash);
  const previousHundredGames = getPreviousGames();
  if (gameResult === 1) {
    gameResult=+' "no"';
  }
  if (gameResult <= 3) {
    gameResult=+' "maybe"';
  }
  if (gameResult <= 10) {
    gameResult+= ' "yes"';
  }
  return { gameResult, previousHundredGames };
}

检查此链接以查看它的实际效果, https://codesandbox.io/s/crash-forked-f7fb7


推荐阅读