index.ts 997 B

12345678910111213141516171819202122232425262728293031
  1. // @ts-nocheck
  2. /**
  3. * 生成一个数字范围的数组
  4. * @param start 范围的起始值
  5. * @param end 范围的结束值
  6. * @param step 步长,默认为 1
  7. * @param fromRight 是否从右侧开始生成,默认为 false
  8. * @returns 生成的数字范围数组
  9. */
  10. export function range(start: number, end: number, step: number = 1, fromRight: boolean = false): number[] {
  11. let index = -1;
  12. // 计算范围的长度
  13. let length = Math.max(Math.ceil((end - start) / (step || 1)), 0);
  14. // 创建一个长度为 length 的数组
  15. const result = new Array(length);
  16. // 使用循环生成数字范围数组
  17. while (length--) {
  18. // 根据 fromRight 参数决定从左侧还是右侧开始填充数组
  19. result[fromRight ? length : ++index] = start;
  20. start += step;
  21. }
  22. return result;
  23. }
  24. // 示例
  25. // console.log(range(0, 5)); // 输出: [0, 1, 2, 3, 4]
  26. // console.log(range(1, 10, 2, true)); // 输出: [9, 7, 5, 3, 1]
  27. // console.log(range(5, 0, -1)); // 输出: [5, 4, 3, 2, 1]