首页 > 其他 > 详细

[TypeScript] Create random integers in a given range

时间:2017-05-01 23:09:05      阅读:388      评论:0      收藏:0      [点我收藏+]

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

原文:http://www.cnblogs.com/Answer1215/p/6793454.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!