helpers.js
2.28 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
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)
}