-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathrange.ts
90 lines (81 loc) · 2.57 KB
/
range.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
import eq from './eq'
import {isArrayLike} from './internal/array'
import isObject from './isObject'
const INFINITY = 1 / 0
const reIsUint = /^(?:0|[1-9]\d*)$/
const baseRange = (start: number, end: number, step: number) => {
let length = Math.max(Math.ceil((end - start) / (step || 1)), 0)
const result = Array(length)
let index = -1
while (length--) {
result[++index] = start
// eslint-disable-next-line no-param-reassign
start += step
}
return result
}
function isIndex(value: number | undefined, length: number) {
if (value === undefined) {
return Number.MAX_SAFE_INTEGER
}
const type = typeof value
// eslint-disable-next-line no-param-reassign
length = length == null ? Number.MAX_SAFE_INTEGER : length
return (
!!length &&
(type === 'number' || (type !== 'symbol' && reIsUint.test(String(value)))) &&
value > -1 &&
value % 1 === 0 &&
value < length
)
}
function toFinite(value: number) {
if (!value) {
return value === 0 ? value : 0
}
// eslint-disable-next-line no-param-reassign
value = Number(value)
if (value === INFINITY || value === -INFINITY) {
const sign = value < 0 ? -1 : 1
return sign * Number.MAX_VALUE
}
return value
}
function isIterateeCall(value: number, index: number | undefined, object: Record<string, unknown>) {
if (!isObject(object)) {
return false
}
if (typeof index === 'undefined') {
return false
}
if (
typeof index === 'number'
? isArrayLike(object) && isIndex(index, object.length)
: typeof index === 'string' && index in object
) {
return eq(index ? [index] : Symbol('any'), value)
}
return false
}
export const range = (start: number, end?: number, step?: number) => {
if (step && typeof step !== 'number' && isIterateeCall(start, end, step)) {
// eslint-disable-next-line no-param-reassign
end = step = undefined
}
// Ensure the sign of `-0` is preserved.
// eslint-disable-next-line no-param-reassign
start = toFinite(start)
if (end === undefined) {
// eslint-disable-next-line no-param-reassign
end = start
// eslint-disable-next-line no-param-reassign
start = 0
} else {
// eslint-disable-next-line no-param-reassign
end = toFinite(end)
}
// eslint-disable-next-line no-param-reassign
step = step === undefined ? (start < end ? 1 : -1) : toFinite(step)
return baseRange(start, end, step)
}
export default range