helpers.js 2.28 KB
import { formatPrice } from './formatters'

export const debounce = (func, wait) => {
  let timeout
  return function executedFunction(...args) {
    const later = () => {
      clearTimeout(timeout)
      func(...args)
    }
    clearTimeout(timeout)
    timeout = setTimeout(later, wait)
  }
}

export const generateOrderNumber = () => {
  const timestamp = Date.now().toString()
  const random = Math.floor(Math.random() * 1000).toString().padStart(3, '0')
  return `ORD-${timestamp}-${random}`
}

export const calculateOrderTotals = (items) => {
  const subtotal = items.reduce((total, item) => total + (item.price * item.quantity), 0)
  const shipping = subtotal > 50 ? 0 : 5.99 // Free shipping over $50
  const tax = subtotal * 0.1 // 10% tax
  const total = subtotal + shipping + tax

  return {
    subtotal: formatPrice(subtotal),
    shipping: formatPrice(shipping),
    tax: formatPrice(tax),
    total: formatPrice(total),
    raw: { subtotal, shipping, tax, total }
  }
}

export const validateForm = (formData, rules) => {
  const errors = {}

  Object.keys(rules).forEach(field => {
    const value = formData[field]
    const fieldRules = rules[field]

    if (fieldRules.required && (!value || value.trim() === '')) {
      errors[field] = `${field} is required`
      return
    }

    if (fieldRules.minLength && value && value.length < fieldRules.minLength) {
      errors[field] = `${field} must be at least ${fieldRules.minLength} characters`
      return
    }

    if (fieldRules.pattern && value && !fieldRules.pattern.test(value)) {
      errors[field] = fieldRules.message || `${field} is invalid`
      return
    }

    if (fieldRules.validate && value) {
      const customError = fieldRules.validate(value, formData)
      if (customError) {
        errors[field] = customError
      }
    }
  })

  return {
    isValid: Object.keys(errors).length === 0,
    errors
  }
}

export const formatFileSize = (bytes) => {
  if (bytes === 0) return '0 Bytes'
  const k = 1024
  const sizes = ['Bytes', 'KB', 'MB', 'GB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}

export const getInitials = (name) => {
  return name
    .split(' ')
    .map(part => part.charAt(0))
    .join('')
    .toUpperCase()
    .slice(0, 2)
}