01 
02 /*
03  *  Descripter 1.0 - Java Script Engines
04  *  Copyright (C) 2010-2015  Jianjun Liu (J.J.Liu)
05  *  
06  *  This program is free software: you can redistribute it and/or modify
07  *  it under the terms of the GNU Affero General Public License as published by
08  *  the Free Software Foundation, either version 3 of the License, or
09  *  (at your option) any later version.
10  *  
11  *  This program is distributed in the hope that it will be useful,
12  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
13  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  *  GNU Affero General Public License for more details.
15  *  
16  *  You should have received a copy of the GNU Affero General Public License
17  *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
18  */
19 
20 package org.descripter.js.api;
21 
22 import java.util.Set;
23 
24 /**
25  * <p>An abstract class of {@link Script} {@link Context}s to emulate the for-in statements in JavaScript.</p>
26  * 
27  * @author <a href="mailto:jianjunliu@126.com">J.J.Liu (Jianjun Liu)</a> at <a href="http://www.descripter.org" target="_blank">http://www.descripter.org</a>
28  * @since Descripter 1.0
29  */
30 public abstract class For<W extends Script<?>> extends Script<W>
31 {
32     private final Objective<?> base;
33     private final Var var;
34 
35     /**
36      * <p>Constructs a script context of this type.</p>
37      * @param with The containing script context.
38      * @param base The base object to loop in
39      * @param key The {@link Key} of the looping variable
40      * @since Descripter 1.0
41      */
42     protected For(W with, Object base, Key key) {
43         super(with);
44         this.base = object(base);
45         var = my(key);
46     }
47 
48     /**
49      * <p>Constructs a script context of this type.</p>
50      * @param with The containing script context.
51      * @param base The base object to loop in
52      * @param var A new looping {@link Var}
53      * @since Descripter 1.0
54      */
55     protected For(W with, Object base, Var var) {
56         super(with);
57         this.base = object(base);
58         this.var = var;
59     }
60 
61     /**
62      * <p>An abstract method to be executed on each loop.</p>
63      * <p>Subclasses need to concretely implement this method.</p>
64      * @since Descripter 1.0
65      */
66     protected abstract void each();
67 
68     /**
69      * <p>Executes the script context of this type.</p>
70      * @since Descripter 1.0
71      */
72     @Override
73     public final void run() {
74         if (base != null) {
75             Set<Key> keys = base.keys();
76             for (Key k : keys) {
77                 var.assign(k);
78                 each();
79             }
80         }
81     }
82 }