Skip to content

Commit

Permalink
拡張メソッドの例を追加
Browse files Browse the repository at this point in the history
  • Loading branch information
kuramapommel committed Sep 10, 2024
1 parent a5fe005 commit 58bf423
Show file tree
Hide file tree
Showing 2 changed files with 89 additions and 0 deletions.
63 changes: 63 additions & 0 deletions sample/src/libs/dates/__tests__/index.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
import '@/libs/dates'
import { describe, expect, test } from 'vitest'

describe('libs/dates', () => {
describe('between', () => {
test('デフォルト状態では、以上かつ以下に含まれるとき true', async () => {
expect(
new Date('2021-01-01 00:01:00').between({
start: new Date('2021-01-01 00:01:00'),
end: new Date('2021-01-01 00:01:00'),
}),
).toBe(true)
})

test('デフォルト状態では、以上かつ以下に含まれないとき false:下限', async () => {
expect(
new Date('2021-01-01 00:00:59').between({
start: new Date('2021-01-01 00:01:00'),
end: new Date('2021-01-01 00:01:00'),
}),
).toBe(false)
})

test('デフォルト状態では、以上かつ以下に含まれないとき false:上限', async () => {
expect(
new Date('2021-01-01 00:01:01').between({
start: new Date('2021-01-01 00:01:00'),
end: new Date('2021-01-01 00:01:00'),
}),
).toBe(false)
})

test('isOrMore=false では、超過かつ以下に含まれるとき true', async () => {
expect(
new Date('2021-01-01 00:01:00').between({
start: new Date('2021-01-01 00:00:59'),
end: new Date('2021-01-01 00:01:00'),
isOrMore: true,
}),
).toBe(true)
})

test('isOrMore=false では、超過に含まれないとき false', async () => {
expect(
new Date('2021-01-01 00:00:59').between({
start: new Date('2021-01-01 00:00:59'),
end: new Date('2021-01-01 00:01:00'),
isOrMore: false,
}),
).toBe(false)
})

test('isOrLess=false では、未満に含まれないとき false', async () => {
expect(
new Date('2021-01-01 00:01:01').between({
start: new Date('2021-01-01 00:01:00'),
end: new Date('2021-01-01 00:01:01'),
isOrLess: false,
}),
).toBe(false)
})
})
})
26 changes: 26 additions & 0 deletions sample/src/libs/dates/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
declare global {
interface Date {
between(params: {
start: Date
end: Date
isOrMore?: boolean
isOrLess?: boolean
}): boolean
}
}

Date.prototype.between = function ({
start,
end,
isOrMore = true,
isOrLess = true,
}) {
const baseTime = this.getTime()
const startTime = start.getTime()
const endTime = end.getTime()

const startCompare = isOrMore ? baseTime >= startTime : baseTime > startTime
const endCompare = isOrLess ? baseTime <= endTime : baseTime < endTime

return startCompare && endCompare
}

0 comments on commit 58bf423

Please sign in to comment.