Any improvements, shorter, more idiomatic (golf?) Nim?
import times, algorithm
var today = now()
var sq: seq[string]
for i in 1..3:
var duration = initDuration(days = i)
var next_day = today + duration
sq.add($next_day.format("dddd, dd-MMM-YYYY"))
var reversed_dzien = reversed sq
for e in reversed_dzien:
echo e
# Tuesday, 01-Jun-2021
# Monday, 31-May-2021
# Sunday, 30-May-2021
Not so much about idiomatic/shorter, but more for performance/efficiency. IIRC reversed returns a new seq and therefore requires allocation. Use reverse to do reversal in place. Or you can do a for loop on the index in decreasing order to avoid reverse altogether.
Also, if you know the number of items beforehand you can use an array to allocate on stack.
Using my chrono ( https://github.com/treeform/chrono ) library and countdown you can go pretty short:
import chrono, times
for i in countdown(2, 0):
var cal = Timestamp(epochTime()).calendar
cal.add(Day, i)
echo cal.format("{weekday}, {day/2}-{month/n/3}-{year}")
Tuesday, 01-Jun-2021
Monday, 31-May-2021
Sunday, 30-May-2021
Its odd that you chose 3 letter month names but 2 digit dates (I would have gone variable 1 or 2 digit days).If the dates in your seq are stored as "YYYY-MM-dd" you can sort them alphanumerically using sort.
Then I converted them back to the format you used incase that is a requirement.
import algorithm, sequtils, times
var dates = @["2021-05-31", "1972-07-01", "2020-01-31", "1969-07-01"]
dates.sort(SortOrder.Descending)
for date in dates:
echo date.parse(initTimeFormat("YYYY-MM-dd")).format("dddd, dd-MMM-YYYY")
you can use countdown:
import times, algorithm
var today = now()
var sq: seq[string]
for i in countdown(3, 1):
var duration = initDuration(days = i)
var next_day = today + duration
sq.add($next_day.format("dddd, dd-MMM-YYYY"))
for e in sq:
echo e
# Friday, 04-Jun-2021
# Thursday, 03-Jun-2021
# Wednesday, 02-Jun-2021
If you know the number of entries up front, you can also do something like this and pre-allocate the sequence:
import times, algorithm
const limit = 3
let today = now()
var sq = newSeq[string](limit)
for i in 1..3:
var duration = initDuration(days = i)
var next_day = today + duration
sq[limit - i] = $next_day.format("dddd, dd-MMM-YYYY")
for e in sq:
echo e