-
Notifications
You must be signed in to change notification settings - Fork 88
Expand file tree
/
Copy pathmax-age.html
More file actions
212 lines (185 loc) · 7.67 KB
/
Copy pathmax-age.html
File metadata and controls
212 lines (185 loc) · 7.67 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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
---
layout: page
title: Fuzzy max-age Calculator
page-class: page--max-age
meta: "Cache-Control’s max-age isn’t the most intuitive way of defining time. This calculator has your back."
permalink: /max-age/
lux: max-age Calculator
main: "/wp-content/uploads/2024/10/max-age-main.png"
---
<p><a
href="/2019/03/cache-control-for-civilians/"><code>Cache-Control</code></a>’s
<a href="/2023/10/what-is-the-maximum-max-age/"><code>max-age</code></a>
directive accepts a duration in seconds, but seconds aren’t particularly
human-friendly. This calculator allows you to specify <code>max-age</code> in
much more palatable terms and end up with a compliant <code>max-age</code>
format. Alternatively, you can paste an existing <code>max-age</code> value and
get its human-friendly equivalent.</p>
<p><strong>Give it a go!</strong></p>
<style>
.c-input-text--max-age {
width: 100%;
}
</style>
<p>
<label for="jsInput">Enter a time period (e.g. ‘a day’, ‘eight weeks’, ‘6 months’, ‘10 seconds’, ‘forever’) or seconds (e.g. 3600):</label>
<input type="text" class="c-input-text c-input-text--max-age" id="jsInput" name="max-age-input" placeholder="e.g. two months and 30 seconds" autofocus>
</p>
<ul>
<li><code><strong>Cache-Control:</strong> </code><output id="jsOutput"></output></li>
<li><strong>Human-friendly version:</strong> <output id="jsOutputHuman"></output></li>
</ul>
<script>
// Set up a word–number map
const wordToNumber = {
'zero': 0,
'one': 1,
'two': 2,
'three': 3,
'four': 4,
'five': 5,
'six': 6,
'seven': 7,
'eight': 8,
'nine': 9,
'ten': 10,
'eleven': 11,
'twelve': 12,
'thirteen': 13,
'fourteen': 14,
'fifteen': 15,
'sixteen': 16,
'seventeen': 17,
'eighteen': 18,
'nineteen': 19,
'twenty': 20,
'thirty': 30,
'forty': 40,
'fifty': 50,
'sixty': 60,
'seventy': 70,
'eighty': 80,
'ninety': 90
};
// Conversion factors
const secondsPerMinute = 60;
const secondsPerHour = 60 * secondsPerMinute;
const secondsPerDay = 24 * secondsPerHour;
const secondsPerWeek = 7 * secondsPerDay;
const secondsPerMonth = 30 * secondsPerDay; // Approximate for 30 days
const secondsPerYear = 365 * secondsPerDay;
// Debounce function
function debounce(fn, delay) {
let timeout;
return function(...args) {
clearTimeout(timeout);
timeout = setTimeout(() => fn.apply(this, args), delay);
};
}
function calculateMaxAge() {
const input = document.getElementById('jsInput').value.trim().toLowerCase();
const output = document.getElementById('jsOutput');
const outputHuman = document.getElementById('jsOutputHuman');
let maxAge = 0;
// Check if input is a number (in seconds) to reverse engineer
if (!isNaN(input) && input !== '') {
let seconds = Math.abs(parseInt(input)); // Convert to absolute value
output.textContent = 'max-age=' + seconds;
outputHuman.textContent = humanizeTime(seconds);
return;
}
// Error checking for invalid inputs
if (!input) {
output.textContent = 'Invalid time period: please try again.';
return;
}
// Split input by ‘and’ to handle multiple time parts (e.g., ‘2 hours and 30 seconds’)
const parts = input.split('and');
parts.forEach(part => {
if (part.includes('forever')) {
maxAge = 2147483648; // Maximum allowed value for max-age
} else if (part.includes('second')) {
maxAge += Math.abs(parseTime(part)) * 1;
} else if (part.includes('minute')) {
maxAge += Math.abs(parseTime(part)) * secondsPerMinute;
} else if (part.includes('hour')) {
maxAge += Math.abs(parseTime(part)) * secondsPerHour;
} else if (part.includes('day')) {
maxAge += Math.abs(parseTime(part)) * secondsPerDay;
} else if (part.includes('week')) {
maxAge += Math.abs(parseTime(part)) * secondsPerWeek;
} else if (part.includes('month')) {
maxAge += Math.abs(parseTime(part)) * secondsPerMonth;
} else if (part.includes('year')) {
maxAge += Math.abs(parseTime(part)) * secondsPerYear;
} else {
output.textContent = 'Error: Unsupported time format.';
return;
}
});
// Ensure max-age doesn’t exceed the specced limit:
// https://csswizardry.com/2023/10/what-is-the-maximum-max-age/
if (maxAge > 2147483648) {
maxAge = 2147483648;
}
// Display the result
output.textContent = 'max-age=' + maxAge;
outputHuman.textContent = humanizeTime(maxAge);
}
function parseTime(input) {
// Extract the number part (digit or word) and convert it to an actual
// number.
const numberMatch = input.match(/(\d+|\b(?:one|two|three|four|five|six|seven|eight|nine|ten|eleven|twelve|thirteen|fourteen|fifteen|sixteen|seventeen|eighteen|nineteen|twenty|thirty|forty|fifty|sixty|seventy|eighty|ninety)\b)/);
if (!numberMatch) {
return 1; // Default to 1 if no number is provided (e.g., ‘a day’)
}
const numberString = numberMatch[0];
let number = parseInt(numberString);
// If the number is a word, convert it using the wordToNumber map
if (isNaN(number)) {
number = wordToNumber[numberString];
}
return Math.abs(number) || 1; // Return the absolute value, or else return 1
}
// Function to convert seconds into human-friendly time format
function humanizeTime(seconds) {
const years = Math.floor(seconds / secondsPerYear);
seconds %= secondsPerYear;
const months = Math.floor(seconds / secondsPerMonth);
seconds %= secondsPerMonth;
const days = Math.floor(seconds / secondsPerDay);
seconds %= secondsPerDay;
const hours = Math.floor(seconds / secondsPerHour);
seconds %= secondsPerHour;
const minutes = Math.floor(seconds / secondsPerMinute);
seconds %= secondsPerMinute;
const parts = [];
if (years) parts.push(`${years} year${years > 1 ? 's' : ''}`);
if (months) parts.push(`${months} month${months > 1 ? 's' : ''}`);
if (days) parts.push(`${days} day${days > 1 ? 's' : ''}`);
if (hours) parts.push(`${hours} hour${hours > 1 ? 's' : ''}`);
if (minutes) parts.push(`${minutes} minute${minutes > 1 ? 's' : ''}`);
if (seconds) parts.push(`${seconds} second${seconds > 1 ? 's' : ''}`);
return parts.length > 0 ? parts.join(' and ') : '0 seconds';
}
// Allow folk to hot-link a specific value
const urlParams = new URLSearchParams(window.location.search);
const valueParam = urlParams.get('value');
if (valueParam && !isNaN(valueParam) && Number(valueParam) > 0) {
const input = document.getElementById('jsInput');
input.value = valueParam;
calculateMaxAge();
}
// Attach the input event listener with debounce
document.getElementById('jsInput').addEventListener('input', debounce(calculateMaxAge, 300));
</script>
<hr />
<p><small>Disclaimer: This <code>max-age</code> calculator aims to provide convenient
and human-friendly conversions between time periods and cache durations. While
I strive for accuracy, there may be edge cases or unexpected behavior in certain
input formats. As this tool interprets natural language and various time units,
I encourage users to verify important calculations and be mindful of potential
inaccuracies in highly complex inputs. I welcome feedback and suggestions! If
you encounter any issues, or if you’d like to contribute improvements, please
feel free to submit them to the GitHub repo at
<a href="https://github.com/csswizardry/csswizardry.github.com/blob/master/max-age.md">github.com/csswizardry/csswizardry.github.com</a>.</small></p>