Browse Source

Add date predicate (#26)

iss58
Sam Verschueren 7 years ago
committed by Sindre Sorhus
parent
commit
f2be585bf2
  1. 8
      source/index.ts
  2. 31
      source/lib/predicates/date.ts
  3. 19
      source/test/date.ts

8
source/index.ts

@ -4,6 +4,7 @@ import {StringPredicate} from './lib/predicates/string';
import {NumberPredicate} from './lib/predicates/number';
import {BooleanPredicate} from './lib/predicates/boolean';
import {ArrayPredicate} from './lib/predicates/array';
import {DatePredicate} from './lib/predicates/date';
export interface Ow {
(value: any, predicate: Predicate): void;
@ -23,6 +24,10 @@ export interface Ow {
* Test the value to be an array.
*/
array: ArrayPredicate;
/**
* Test the value to be a Date.
*/
date: DatePredicate;
}
const main = (value: any, predicate: Predicate) => {
@ -46,6 +51,9 @@ Object.defineProperties(main, {
},
array: {
get: () => new ArrayPredicate()
},
date: {
get: () => new DatePredicate()
}
});

31
source/lib/predicates/date.ts

@ -0,0 +1,31 @@
import {Predicate, Context} from './predicate';
export class DatePredicate extends Predicate<Date> {
constructor(context?: Context) {
super('date', context);
}
/**
* Test a date to be before another date.
*
* @param date Maximum value.
*/
before(date: Date) {
return this.addValidator({
message: value => `Expected ${value.toISOString()} to be before ${date.toISOString()}`,
validator: value => value.getTime() < date.getTime()
});
}
/**
* Test a date to be before another date.
*
* @param date Minimum value.
*/
after(date: Date) {
return this.addValidator({
message: value => `Expected ${value.toISOString()} to be after ${date.toISOString()}`,
validator: value => value.getTime() > date.getTime()
});
}
}

19
source/test/date.ts

@ -0,0 +1,19 @@
import test from 'ava';
import m from '..';
test('date', t => {
t.notThrows(() => m(new Date(), m.date));
t.throws(() => m('12', m.date), 'Expected argument to be of type `date` but received type `string`');
});
test('date.before', t => {
t.notThrows(() => m(new Date('2017-11-25'), m.date.before(new Date('2017-11-26'))));
t.notThrows(() => m(new Date('2017-11-25T12:00:00Z'), m.date.before(new Date('2017-11-25T12:00:01Z'))));
t.throws(() => m(new Date('2017-11-25T12:00:00Z'), m.date.before(new Date('2017-11-25T12:00:00Z'))), 'Expected 2017-11-25T12:00:00.000Z to be before 2017-11-25T12:00:00.000Z');
});
test('date.after', t => {
t.notThrows(() => m(new Date('2017-11-26'), m.date.after(new Date('2017-11-25'))));
t.notThrows(() => m(new Date('2017-11-26T12:00:00Z'), m.date.after(new Date('2017-11-26T11:59:59Z'))));
t.throws(() => m(new Date('2017-11-26T12:00:00Z'), m.date.after(new Date('2017-11-26T12:00:00Z'))), 'Expected 2017-11-26T12:00:00.000Z to be after 2017-11-26T12:00:00.000Z');
});
Loading…
Cancel
Save