Skip to content

Commit 848ca1f

Browse files
committed
meetup: add code to write new descriptions
This helps understand the logic used to write the new descriptions.
1 parent 9ed28a9 commit 848ca1f

File tree

1 file changed

+69
-0
lines changed

1 file changed

+69
-0
lines changed

exercises/meetup/newdesc.rb

Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
require 'json'
2+
3+
j = JSON.parse(File.read(File.join(__dir__, 'canonical-data.json')))
4+
5+
def ord(n)
6+
case n
7+
when 1; '1st'
8+
when 2; '2nd'
9+
when 3; '3rd'
10+
when 21; '21st'
11+
when 22; '22nd'
12+
when 23; '23rd'
13+
when 31; '31st'
14+
else "#{n}th"
15+
end
16+
end
17+
18+
def mod_desc_for_range(c, week, first, last)
19+
raise "bad #{c['input']['week']} != #{week}" if c['input']['week'] != week
20+
21+
if c['expected'].end_with?('-%02d' % first)
22+
c['description'] = "when #{week} #{c['input']['dayofweek']} is the #{ord(first)}, the first day of the #{week} week"
23+
elsif c['expected'].end_with?('-%02d' % last)
24+
c['description'] = "when #{week} #{c['input']['dayofweek']} is the #{ord(last)}, the last day of the #{week} week"
25+
else
26+
c['description'] = "when #{week} #{c['input']['dayofweek']} is some day in the middle of the #{week} week"
27+
end
28+
end
29+
30+
j['cases'].each { |c|
31+
case c['input']['week']
32+
when 'teenth'; mod_desc_for_range(c, 'teenth', 13, 19)
33+
when 'first'; mod_desc_for_range(c, 'first', 1, 7)
34+
when 'second'; mod_desc_for_range(c, 'second', 8, 14)
35+
when 'third'; mod_desc_for_range(c, 'third', 15, 21)
36+
when 'fourth'; mod_desc_for_range(c, 'fourth', 22, 28)
37+
when 'last'
38+
month = Integer(c['expected'].split(?-, 3)[1], 10)
39+
day = Integer(c['expected'].split(?-, 3)[2], 10)
40+
dow = c['input']['dayofweek']
41+
if month == 2 && day == 29
42+
c['description'] = "when last #{dow} in February in a leap year is the 29th"
43+
elsif month == 2 && day == 22
44+
c['description'] = "when last #{dow} in February in a non-leap year is not the 29th"
45+
elsif month == 12 && day == 31
46+
c['description'] = "last #{dow} in December that also happens to be the last day of the year"
47+
else
48+
c['description'] = "last #{dow} in a month with #{day > 28 ? 'five' : 'four'} #{dow}s"
49+
end
50+
else
51+
$stderr.puts("no new description for #{c['description']}")
52+
end
53+
}
54+
55+
seen = {}
56+
# dedup by notating some cases with "another"
57+
j['cases'].each { |c|
58+
desc = c['description']
59+
if seen[desc]
60+
new_desc = desc.include?('some day') ? desc.sub('some day', 'another day') : desc.sub('a month with', 'another month with')
61+
raise "couldn't fix #{desc}" if new_desc == desc
62+
raise "tried to fix #{desc} but even #{new_desc} was already seen" if seen[new_desc]
63+
seen[new_desc] = true
64+
c['description'] = new_desc
65+
end
66+
seen[desc] = true
67+
}
68+
69+
puts JSON.pretty_generate(j)

0 commit comments

Comments
 (0)