--[[----------------------------------------------------------------------------

WFRxDynamicArraySlice.lua

--------------------------------------------------------------------------------

ADOBE CONFIDENTIAL
------------------
Copyright 2015 Adobe Systems Incorporated
All Rights Reserved.

NOTICE: All information contained herein is, and remain the property of
Adobe Systems Incorporated and its suppliers, if any. The intellectual and
technical concepts contained herein are proprietary to Adobe Systems
Incorporated and its suppliers and may be covered by U.S. and Foreign
Patents, patents in process, and are protected by trade secret or copyright
law. Dissemination of this information or reproduction of this material is
strictly forbidden unless prior written permission is obtained from
Adobe Systems Incorporated.

--------------------------------------------------------------------------------

WFRxDynamicArraySlice consumes a sequence of array-valued tables combined with
a sequence of array bounds (start, end indices) and returns the slice of the
first table that falls within the bounds.

It is meant to be used as a selector function for the Rx.Observable:combineLatest
operator.

For instance:

	local logger = WFLogger( 'sample' )
		:setLevel( 'debug' )

	local source = Rx.Subject()
	local bounds = Rx.Subject()

	source
		:combineLatest( WFRxDynamicArraySlice, bounds )
		:subscribe(
			function( slice )
				logger:debugf( "\n>> slice = %s\n", slice )
			end,
			function( message )
				logger:errorf( "\n>> ERROR: %s\n\n", message )
			end )

	source:onNext( {} )
		-- Nothing happens (no bounds yet).

	source:onNext( { 1, 3, 5, 7 } )
		-- Nothing happens (no bounds yet).

	bounds:onNext( 1, 2 )

	>> slice = { 1, 3 }

	bounds:onNext( 2, 3 )

	>> slice = { 3, 5 }

	source:onNext( { 1, 4, 7, 11 } )

	>> slice = { 4, 7 }

	source:onNext( "not a table" )

	>> ERROR: (message TBD)

------------------------------------------------------------------------------]]

	-- WF.core.utils
local WFArguments = require 'WFArguments'


--------------------------------------------------------------------------------

local check = assert( WFArguments.check )
local max = assert( math.max )
local min = assert( math.min )
local floor = assert( math.floor )

--------------------------------------------------------------------------------

return function( source, startIndex, endIndex )

	check( 'table', 'number', 'number' )

	startIndex = floor( max( startIndex, 1 ) )
	endIndex = floor( min( endIndex, #source ) )

	local result = {}
	local n = 1

	for i = startIndex, endIndex do
		result[ n ] = source[ i ]
		n = n + 1
	end

	return result

end
