Vibescript Showcase
Reshape a list
Paginate, window, and sample a flat list with each_slice, each_cons, take, drop, and values_at.
Source
showcase/collections/reshape.vibe
# title: Reshape a list
# category: Vibescript Showcase
# difficulty: Showcase
# summary: Paginate, window, and sample a flat list with each_slice, each_cons, take, drop, and values_at.
# description: The 1.0 array library adds the Ruby slicing vocabulary, so turning a stream of records into pages or rolling windows no longer needs manual index bookkeeping.
# 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 to execute run from this example.