Skip to content

Instantly share code, notes, and snippets.

@fredyr
Created January 17, 2013 20:14
Show Gist options
  • Save fredyr/4559314 to your computer and use it in GitHub Desktop.
Save fredyr/4559314 to your computer and use it in GitHub Desktop.
Gilded rose hack
def update(item_original, attr, value):
"""
Returns a new dict with attr=value
item = {"name": "+5 Dexterity Vest", "sell_in": 10, "quality": 20}
=> {'sell_in': 10, 'quality': 20, 'name': '+5 Dexterity Vest'}
update(item, 'quality', 5)
=> {'sell_in': 10, 'quality': 5, 'name': '+5 Dexterity Vest'}
"""
item = item_original.copy()
item[attr] = value
return item
def enforce_range(quality):
if quality < 0:
return 0
if quality > 50:
return 50
return quality
def backstage(quality, sell_in):
conds = zip([0, 5, 10], [0, quality + 3, quality + 2])
for (d, q) in conds:
if sell_in <= d:
return q
return quality + 1
def double_rate(quality, sell_in, sign):
if sell_in <= 0:
return quality + 2 * sign
else:
return quality + 1 * sign
def aged_brie(quality, sell_in):
return double_rate(quality, sell_in, 1)
def sulfuras(quality, sell_in):
return quality
def decrease_quality(quality, sell_in):
return double_rate(quality, sell_in, -1)
def decrease_sell_in(value):
return value - 1
def update_quality(item):
special_quality_cases = {
"Backstage passes to a TAFKAL80ETC concert":
lambda q, s: enforce_range(backstage(q, s)),
"Aged Brie":
lambda q, s: enforce_range(aged_brie(q, s)),
"Sulfuras, Hand of Ragnaros":
sulfuras,
}
if item['name'] in special_quality_cases:
q = special_quality_cases[item['name']](item['quality'], item['sell_in'])
else:
q = enforce_range(decrease_quality(item['quality'], item['sell_in']))
return q
def update_sell_in(item):
special_sell_in_cases = {
"Sulfuras, Hand of Ragnaros":
lambda s: s
}
if item['name'] in special_sell_in_cases:
d = special_sell_in_cases[item['name']](item['sell_in'])
else:
d = decrease_sell_in(item['sell_in'])
return d
def update_single_item(item):
q = update_quality(item)
s = update_sell_in(item)
return update(update(item, 'quality', q), 'sell_in', s)
def update_items(items):
return [update_single_item(item) for item in items]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment