Skip to content

Feature: Time-Travel and Temporal Data Generation #66

@Goldziher

Description

@Goldziher

Feature: Time-Travel and Temporal Data Generation

Add sophisticated time-based data generation capabilities for creating realistic historical data, temporal relationships, and time-series testing scenarios.

Problem Statement

Testing applications often requires:

  • Historical data with realistic timestamps
  • Temporal relationships between entities (created before updated, etc.)
  • Business hours and timezone-aware data
  • Time-series data for analytics testing
  • Consistent "as-of" date generation

Proposed Features

1. Time-Travel API

// Generate data as if it was created on a specific date
const factory = new Factory<Order>((faker) => ({
  id: faker.string.uuid(),
  createdAt: faker.date.recent(),
  status: faker.helpers.arrayElement(['pending', 'shipped', 'delivered'])
}));

// Generate as of January 1, 2023
const historicalOrder = factory.asOf('2023-01-01').build();
// createdAt will be before or on 2023-01-01

// Time travel with context
const timeTravel = factory.timeTravel({
  currentDate: '2023-06-15',
  timezone: 'America/New_York',
  businessHours: { start: 9, end: 17 }
});

const order = timeTravel.build();

2. Timeline Generation

// Generate a timeline of events
const events = factory.timeline({
  from: '2020-01-01',
  to: '2023-12-31',
  interval: 'monthly', // 'daily', 'weekly', 'monthly', 'quarterly', 'yearly'
  count: 36 // Or use interval to determine count
});

// Generate with realistic patterns
const orders = OrderFactory.timeline({
  from: '2023-01-01',
  to: '2023-12-31',
  pattern: 'business-realistic', // More orders on weekdays, peak in December
  variance: 0.2 // 20% random variance
});

3. Temporal Relationships

const BlogPostFactory = new Factory<BlogPost>((faker) => ({
  id: faker.string.uuid(),
  createdAt: faker.temporal.past(),
  updatedAt: faker.temporal.after('createdAt'),
  publishedAt: faker.temporal.between('createdAt', 'now'),
  lastCommentAt: faker.temporal.afterOrNull('publishedAt')
}));

// Ensure temporal consistency
const post = BlogPostFactory.build();
// Guarantees: createdAt < updatedAt, createdAt < publishedAt < now

4. Business Time Generation

// Business hours aware generation
const MeetingFactory = new Factory<Meeting>((faker) => ({
  id: faker.string.uuid(),
  scheduledAt: faker.temporal.businessHours({
    start: 9,
    end: 17,
    timezone: 'America/New_York',
    excludeWeekends: true,
    excludeHolidays: true,
    holidays: ['2023-12-25', '2023-01-01']
  }),
  duration: faker.helpers.arrayElement([30, 60, 90]) // minutes
}));

// Generate working days sequence
const workDays = faker.temporal.businessDays({
  from: '2023-01-01',
  count: 20 // Generate 20 business days
});

5. Time Series Data

// Generate time series with patterns
const MetricsFactory = new Factory<Metric>((faker) => ({
  timestamp: faker.temporal.series(),
  value: faker.temporal.pattern('seasonal', {
    base: 100,
    amplitude: 20,
    period: 'yearly',
    noise: 0.1
  }),
  sensor: faker.helpers.arrayElement(['A', 'B', 'C'])
}));

// Generate with specific patterns
const salesData = SalesFactory.timeSeries({
  from: '2023-01-01',
  to: '2023-12-31',
  interval: 'daily',
  pattern: {
    trend: 'linear-growth', // 'linear-growth', 'exponential', 'logarithmic', 'stable'
    seasonality: 'weekly', // Weekly pattern (lower on weekends)
    events: [
      { date: '2023-11-24', impact: 3.0 }, // Black Friday spike
      { date: '2023-12-25', impact: 0.1 }  // Christmas dip
    ]
  }
});

6. Timezone Support

const GlobalEventFactory = new Factory<GlobalEvent>((faker) => ({
  id: faker.string.uuid(),
  localTime: faker.temporal.localTime('09:00', '17:00'),
  utcTime: faker.temporal.utc(),
  userTimezone: faker.location.timeZone(),
  scheduledAt: faker.temporal.inTimezone('Europe/London')
}));

// Convert between timezones
const event = GlobalEventFactory.build();
const localTime = factory.toTimezone(event.utcTime, event.userTimezone);

Advanced Features

Historical Context

// Generate data with historical context
const HistoricalUserFactory = UserFactory.withTemporalContext({
  // Prices from 2020
  priceIndex: 0.85,
  // Technology available in 2020
  availableFeatures: ['basic', 'premium'],
  // Regulations in effect
  gdprCompliant: false
});

Temporal Constraints

const EventFactory = new Factory<Event>((faker) => ({
  id: faker.string.uuid(),
  startTime: faker.date.future(),
  endTime: faker.temporal.after('startTime', { min: '1 hour', max: '4 hours' }),
  reminderTime: faker.temporal.before('startTime', { exactly: '15 minutes' })
}));

Implementation Details

  1. Date Manipulation

    • Use date-fns or dayjs for date operations
    • Support for various date formats
    • Efficient date arithmetic
  2. Timezone Handling

    • Integration with timezone libraries
    • DST awareness
    • Historical timezone data
  3. Pattern Generation

    • Mathematical models for trends
    • Seasonal decomposition
    • Random walk for realistic variance

Example Use Cases

// E-commerce order history
const orderHistory = OrderFactory.timeline({
  from: '2022-01-01',
  to: '2023-12-31',
  pattern: {
    base: 100, // Base orders per day
    growth: 0.001, // 0.1% daily growth
    seasonality: {
      december: 2.5, // 2.5x orders in December
      july: 0.8 // 20% fewer orders in July
    },
    dayOfWeek: {
      monday: 1.2,
      sunday: 0.7
    }
  }
});

// Social media engagement
const posts = PostFactory.timeline({
  from: '2023-01-01',
  to: '2023-12-31',
  interval: 'hourly',
  pattern: {
    hourOfDay: {
      9: 1.5,  // Morning peak
      12: 2.0, // Lunch peak
      18: 2.5, // Evening peak
      3: 0.2   // Night low
    }
  }
});

// Financial transactions
const transactions = TransactionFactory.timeSeries({
  from: '2023-01-01',
  to: '2023-12-31',
  interval: '15 minutes',
  businessHoursOnly: true,
  pattern: 'market-hours' // Predefined pattern for market activity
});

Testing Requirements

  • Unit tests for temporal relationships
  • Timezone conversion accuracy
  • Business hours calculation tests
  • Pattern generation validation
  • Performance tests for large time series
  • Edge cases (DST transitions, leap years)

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions