~eda-qa/dhlib/main

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
divert(-1)
/* <license>
 * This file is part of the dis-Emi-A HaXe Library. Copyright © edA-qa mort-ora-y
 * For full copyright and license information please refer to doc/license.txt.
 * </license> 
 */
/**
 * Creates a range iterator given a starting point, a target, and a stepping
 * direction/amount.
 *
 * Done via an M4 macro since haxe doesn't handle templated argumetns very well...
 */
 
define( `template', `
define( `_T', $2 )

class RangeIter$1
{
	var at : _T;	//where we're at now
	var dir : _T;	//which direction/step we're taking
	var target : _T;	//to where we're heading (may not be included in results if no within step)
	
	/**
	 * Creates a new inclusive iterator.
	 *
	 * @param	from	[in] where to start from
	 * @param	to	[in] up until and included this value
	 * @param	step	[in] amount to step by (positive or negative) (default = +1, or -1, based on from/to)
	 * @param	allowEmpty [in] causes an assertion if the range is empty (default = true)
	 */
	public function new( from : _T, to : _T, ?step : Null<_T>, ?allowEmpty : Null<Bool> )
	{
		at = from;
		target = to;
		
		if( step == null )
			step = if( at < target ) 1 else -1;
		dir = step;
		
		//check for infinite cases
		Assert.isTrue( 
			(at < target && dir > 0) 
			|| (at > target && dir < 0)
			|| (at == target && dir != 0) 	//special case for a single entry range
			);
			
		//check for empty cases
		if( allowEmpty != null && !allowEmpty )
			Assert.isTrue( hasNext() );
	}
	
	public function hasNext() : Bool
	{
		if( dir < 0 )
			return at >= target;
		return at <= target;
	}
	
	public function next() : _T
	{
		var ret = at;
		at += dir;
		return ret;
	}
}
)	//end of macro
divert