Skip to content

Commit

Permalink
feat: add inRange
Browse files Browse the repository at this point in the history
  • Loading branch information
fjc0k committed Jan 21, 2019
1 parent 1154786 commit f7a1b78
Show file tree
Hide file tree
Showing 3 changed files with 48 additions and 0 deletions.
24 changes: 24 additions & 0 deletions src/inRange.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
export type InRangeInterval = '()' | '(]' | '[)' | '[]'

/**
* 检查 `value` 是否在某区间内。
*
* @param value 要检查的值
* @param start 开始值
* @param end 结束值
* @param [interval='()'] 区间符号
* @returns `value` 在区间内,返回 `true`;`value` 在区间外,返回 `false`。
*/
export default function inRange(
value: number,
start: number,
end: number,
interval: InRangeInterval = '()'
): boolean {
const leftEqual = interval[0] === '['
const rightEqual = interval[1] === ']'
return (
((leftEqual && value === start) || value > start)
&& ((rightEqual && value === end) || value < end)
)
}
1 change: 1 addition & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ export { default as getType } from './getType'
export { default as has } from './has'
export { default as inBrowser } from './inBrowser'
export { default as inNode } from './inNode'
export { default as inRange } from './inRange'
export { default as inWechatMiniProgram } from './inWechatMiniProgram'
export { default as inWechatWebview } from './inWechatWebview'
export { default as isArray } from './isArray'
Expand Down
23 changes: 23 additions & 0 deletions test/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1527,3 +1527,26 @@ describe('sumBy', () => {
expect(vtils.sumBy([vtils.range(0, 10), vtils.range(0, 5)], item => item.length)).toBe(15)
})
})

describe('inRange', () => {
test('开区间', () => {
expect(vtils.inRange(5, 2, 6)).toBeTruthy()
expect(vtils.inRange(2, 2, 6)).toBeFalsy()
expect(vtils.inRange(6, 2, 6)).toBeFalsy()
expect(vtils.inRange(7, 2, 6)).toBeFalsy()
expect(vtils.inRange(2.0001, 2, 6)).toBeTruthy()
expect(vtils.inRange(5.9999, 2, 6)).toBeTruthy()
})
test('闭区间', () => {
expect(vtils.inRange(5, 2, 6, '[]')).toBeTruthy()
expect(vtils.inRange(2, 2, 6, '[]')).toBeTruthy()
expect(vtils.inRange(6, 2, 6, '[]')).toBeTruthy()
expect(vtils.inRange(2.0001, 2, 6, '[]')).toBeTruthy()
expect(vtils.inRange(5.9999, 2, 6, '[]')).toBeTruthy()
})
test('半开半闭区间', () => {
expect(vtils.inRange(2, 2, 6, '(]')).toBeFalsy()
expect(vtils.inRange(2, 2, 6, '[)')).toBeTruthy()
expect(vtils.inRange(6, 2, 6, '(]')).toBeTruthy()
})
})

0 comments on commit f7a1b78

Please sign in to comment.