22
33import com .annimon .ownlang .exceptions .TypeException ;
44import com .annimon .ownlang .lib .*;
5- import java .util .ArrayList ;
6- import java .util .List ;
75
8- import java .util .Map ;
9-
10- public final class functional_filter implements Function {
6+ public final class functional_dropwhile implements Function {
117
128 @ Override
139 public Value execute (Value ... args ) {
1410 Arguments .check (2 , args .length );
11+ if (args [0 ].type () != Types .ARRAY ) {
12+ throw new TypeException ("Array expected in first argument" );
13+ }
1514 if (args [1 ].type () != Types .FUNCTION ) {
1615 throw new TypeException ("Function expected in second argument" );
1716 }
1817
1918 final Value container = args [0 ];
20- final Function consumer = ((FunctionValue ) args [1 ]).getValue ();
21- if (container .type () == Types .ARRAY ) {
22- return filterArray ((ArrayValue ) container , consumer );
23- }
24-
25- if (container .type () == Types .MAP ) {
26- return filterMap ((MapValue ) container , consumer );
27- }
28-
29- throw new TypeException ("Invalid first argument. Array or map expected" );
19+ final Function predicate = ((FunctionValue ) args [1 ]).getValue ();
20+ return dropWhileArray ((ArrayValue ) container , predicate );
3021 }
3122
32- private Value filterArray (ArrayValue array , Function predicate ) {
33- final int size = array .size ();
34- final List <Value > values = new ArrayList <Value >(size );
23+ private Value dropWhileArray (ArrayValue array , Function predicate ) {
24+ int skipCount = 0 ;
3525 for (Value value : array ) {
36- if (predicate .execute (value ) != NumberValue .ZERO ) {
37- values . add ( value ) ;
38- }
26+ if (predicate .execute (value ) != NumberValue .ZERO )
27+ skipCount ++ ;
28+ else break ;
3929 }
40- final int newSize = values .size ();
41- return new ArrayValue (values .toArray (new Value [newSize ]));
42- }
43-
44- private Value filterMap (MapValue map , Function predicate ) {
45- final MapValue result = new MapValue (map .size ());
46- for (Map .Entry <Value , Value > element : map ) {
47- if (predicate .execute (element .getKey (), element .getValue ()) != NumberValue .ZERO ) {
48- result .set (element .getKey (), element .getValue ());
49- }
50- }
51- return result ;
30+
31+ final int size = array .size ();
32+ final Value [] result = new Value [size - skipCount ];
33+ System .arraycopy (array .getCopyElements (), skipCount , result , 0 , result .length );
34+ return new ArrayValue (result );
5235 }
5336}
0 commit comments