I have started auto-generating short-URLs for each of my posts, old and new, and opted to implement Tantek Çelik’s NewBase60 for representing the unique URLs, but I’ve done so with Liquid so it plays nicely with my Jekyll-powered website.
Off the back of the Tantek Çelik’s enlighting and superb work on Whistle1 and NewBase602, I yearned for a way to generate short-URLs for each of my post categories, and figured out a way, albeit a bit over-complicated, using vanilla Jekyll/Liquid.
For example, there is a Note that I published on 08 September 2018, and is the 1st (and only) Note of that day. Let’s look at the page’s short-URL and break down what the code at the end means:
This code is comprised of three parts:
- n — Category (required, 1 character) ↩
- 4wN — Sexagesimal Epoch Days (required, 3 characters) ↩
- 1 — Post Number for the Day (optional, 1 character, default = 1) ↩
Firstly, we need to figure out the category for a particular page. I’m assigning a letter to each category for two reasons: to limit the loop to posts of that type, and to make it such that one can discern the category from the short-URL’s slug.
How do we calculate Epoch days from a given post’s date?
The full ISO 8601 datetime for our example post is 2018-09-08T23:58:42+01:00, and the first step is to convert this to a Unix timestamp (seconds since Epoch), and from there we can divide by 86400 (the number of seconds in a day) to get the number of days since Epoch. Fortunately, this is quite trivial with Jekyll:
Sexagesimal is a number system with 60 as its base and is actually over 5000 years old3! For our short-URLs, the 60 characters are represented by the following:
In order to complete this step, we need to loop through our Epoch days tallying and converting into base 60 until we hit
while loop, so the following won’t work:
However, we can mimic one using a
for loop that counts to a (theoretically) unreachable number, and we can break out of the loop when our condition is met (as with a standard
Much like a
while loop, we are not concerned with the iteration variable, i, we simply want to perform an action until a condition is met—it doesn’t matter how many iterations are required.
Putting it all together, our code now looks like the following, where we are storing our output in the s variable:
The remaining portion of work is to determine how many posts of the given category have been published on the given day, and which of those posts, chronologically, this one is. To do so, we need to add an additional action to our category checks which instructs which category of posts to trawl:
We can use this categorised list of posts to match dates against and build an array of posts under the specific category on the specific day. Looping through this array of posts until we reach the post for which we’re building and pulling out the array index gives us the number we’re looking for:
At last, the following variable becomes available for use: