-
Notifications
You must be signed in to change notification settings - Fork 23
Stream
Streams are an easy way to chain functional operations on array-like structures.
Note that the passed in table is modified directly by all operations. Also, all operations (except AsTable()
, Concat()
and Reduce()
) return the stream object, so you can chain method calls.
To get a stream for a table:
local Stream = Shine.Stream( Table )
Returns the underlying table for the stream.
Returns a string built from the values in the table.
-- Concatenates all values by taking their tostring() representation and adding ", " between them.
local String = Stream:Concat( ", ", tostring )
Filters out values in the table that the given predicate does not return true for.
-- Filter out all values less than or equal to 3.
Stream:Filter( function( Value ) return Value > 3 end )
Runs the given function over all elements without editing the values in the table.
-- Prints every value in the table.
Stream:ForEach( LuaPrint )
Cuts out any values past the given limit.
-- Cuts out all but the first 3 values.
Stream:Limit( 3 )
Replaces all values in the table with the value returned by the mapper function.
-- Negate all values in the table
Stream:Map( function( Value ) return -Value end )
Reduces the values in the stream into a single return value.
Takes two parameters:
- A function that receives the current reducing value, the current stream value, and the current index in the stream.
- An optional starting value. If not provided, the starting value will be the first value in the stream, and the first step will be at the second index.
Returns the value returned by the last call to the provided consumer function.
-- Sum the values in the stream.
Stream:Reduce( function( Sum, Value, Index )
return Sum + Value
end )
Sorts the values in the table using the given comparator. Essentially just table.sort()
.
-- Sort in descending order.
Stream:Sort( function( A, B ) return A > B end )
Sorts the values in the table using the given comparator and the merge sort algorithm. This produces a stable sorting.
-- Sort in descending order.
Stream:StableSort( function( A, B )
return A == B and 0 or ( A > B and -1 or 1 )
end )