Vibescript Showcase
Reshape a list
Split a list into pages and rolling windows, then sample values.
Source
showcase/collections/reshape.vibe
# title: Reshape a list
# category: Vibescript Showcase
# difficulty: Showcase
# summary: Split a list into pages and rolling windows, then sample values.
# description: each_slice builds pages, each_cons builds windows, and take, drop, and values_at select items without manual indexes.
# tags: collections, arrays, enumerable
# vibe: 0.4
def paginate(items, per_page)
pages = []
items.each_slice(per_page) do |page|
pages.push(page)
end
pages
end
def rolling_totals(values, window)
totals = []
values.each_cons(window) do |group|
totals.push(group.sum)
end
totals
end
def run
ids = [101, 102, 103, 104, 105, 106, 107]
readings = [3, 5, 4, 8, 6]
{
pages: paginate(ids, 3),
first_three: ids.take(3),
rest: ids.drop(3),
endpoints: ids.values_at(0, -1),
rolling_totals: rolling_totals(readings, 2)
}
end
Output
Press Run example to run this code.