Skip to content

PTW - Predicate Time Windows

A powerful TypeScript library for parsing and evaluating complex schedule expressions with support for time-based rules, logical operations, and advanced scheduling patterns.

Important: PTW is timezone-agnostic. All timestamps should be provided in UTC milliseconds since epoch.

Library is currently in BETA, expect drastic API changes in major releases

Quick Example

typescript
import { parseExpression, Schedule } from 'ptw'

// Parse business hours expression
const expression = parseExpression('T[9:00..17:00] AND WD[1..5]')

if (!expression.ok) {
  return false
}

// Evaluate for January 2024 (UTC)
const startTime = Date.UTC(2024, 0, 1)
const endTime = Date.UTC(2024, 0, 31, 23, 59, 59, 999)

expression.evaluate(startTime, endTime)

Key Features

  • Expression Parsing: Human-readable schedule expressions
  • Multiple Field Types: Time, date, weekday, month, year, and datetime fields
  • Logical Operations: AND, OR, NOT operations for complex rules
  • Type Safety: Full TypeScript support with result error handling
  • Performance: Built-in caching and optimization
  • References: Reusable schedule expressions
  • Merge Control: Fine-grained control over range merging
  • Timezone Agnostic: Consistent UTC-based operations

Field Types Overview

FieldSyntaxDescriptionExample
TimeT[...]Time ranges within a dayT[9:00..17:00]
WeekDayWD[...]Days of week (1=Mon, 7=Sun)WD[1..5]
DateD[...]Specific datesD[2025-01-15]
MonthM[...]Months (1=Jan, 12=Dec)M[6..8]
MonthDayMD[...]Days within monthsMD[1,15]
YearY[...]Specific yearsY[2025]
DateTimeDT[...]Date and time combinationsDT[2025-01-15T09:00..2024501-15T17:00]
ReferenceREF[...]Named expression referencesREF[holidays]

Logical Operators

OperatorSyntaxDescription
ANDexpr1 AND expr2 or expr1.expr2Both conditions must be true
ORexpr1 OR expr2 or expr1,expr2Either condition can be true
NOTNOT expr or !exprNegation of expression

Common Patterns

Business Hours

typescript
parseExpression('T[9:00..17:00] AND WD[1..5]')

Maintenance Windows

typescript
parseExpression('WD[7] AND T[2:00..6:00]')

Holiday Exclusions

typescript
parseExpression('WD[1..5] AND NOT REF[holidays]')

Quarterly Meetings

typescript
parseExpression('M[3,6,9,12] AND MD[1..7] AND WD[1] AND T[14:00..15:00]')

Rotating Schedules

typescript
parseExpression('WD[2n+1] AND T[8:00..16:00]')

Installation

bash
npm install ptw

Documentation

TypeScript Support

PTW is written in TypeScript and provides comprehensive type definitions for safe, type-checked schedule operations.

typescript
import type { DateTimeRange, IBlock, Result } from 'ptw'

const result: Result<IBlock, Error> = parseExpression('T[9:00..17:00]')

Released under the MIT License.