[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();
});
复制代码

 

posted @   Zhentiw  阅读(466)  评论(0编辑  收藏  举报
编辑推荐:
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
历史上的今天:
2016-05-01 [Javascript] Add a browser build to an npm module
2016-05-01 [Angular 2] ngrx/store
2015-05-01 [ES6] 23. Rest Parameters & Spread Parameters
点击右上角即可分享
微信分享提示