Skip to content

Instantly share code, notes, and snippets.

@kohki-shikata
Last active July 8, 2024 03:02
Show Gist options
  • Save kohki-shikata/f71f3f8100611e1399c771a58aa678c3 to your computer and use it in GitHub Desktop.
Save kohki-shikata/f71f3f8100611e1399c771a58aa678c3 to your computer and use it in GitHub Desktop.
[TypeScript] ランダムな整数を返却する。
// 配列をランダムに出力したいときの添字出力用
// バリデーションには、Joiを使用
// 負の値、小数点には対応しない
import Joi from 'joi'
const schema = Joi.object().keys({
min: Joi.number().min(0),
max: Joi.number().positive()
})
const createRandom = (min: number,max: number): number => {
// validate
const validated = schema.validate({ min, max })
if(validated.error) {
console.log(validated.error)
throw new Error('An error occured.')
}
const value = Math.floor(Math.random() * (max - min) + min);
return value
}
export default createRandom
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment