[TypeScript] Create random integers in a given range

Posted Answer1215

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[TypeScript] Create random integers in a given range相关的知识,希望对你有一定的参考价值。

Learn how to create random integers using javascript / TypeScript.

 

/**
 * Returns a random int between
 * @param start inclusive
 * @param before exclusive
 */
export function randomInt(start: number, before: number) {
  return start + Math.floor(Math.random() * (before - start));
}

 

import { randomInt } from ‘./random‘;

test("Should not include ceiling", () => {
  const res = [];
  for (let index = 0; index < 100; index++) {
    res.push(randomInt(0, 5));
  }
  expect(res.some(x => x === 5)).toBeFalsy();
});

test("Should include one before ceiling", () => {
  const res = [];
  for (let index = 0; index < 100; index++) {
    res.push(randomInt(0, 5));
  }
  expect(res.some(x => x === 4)).toBeTruthy();
});

 

以上是关于[TypeScript] Create random integers in a given range的主要内容,如果未能解决你的问题,请参考以下文章

将 create-react-app 从 javascript 迁移到 typescript

typescript Observable.create

typescript Observable.create

create-react-app 可以与 TypeScript 一起使用吗

使用 typescript 在 create-react-app 中加载 sass

在 create-react-app + typescript 中导入静态 JSON