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.HashMap;
23 
24 /**
25  * <p>Represents a cache of cases emulating the <tt>case</tt> clauses of JavaScript <tt>switch</tt> statements.</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 final class Cases extends Script<Script<?>>
31 {
32     private final HashMap<Object, Integer> map = new HashMap<Object, Integer>();
33     private int next = 0;
34 
35     /**
36      * <p>Constructs a script context of this type.</p>
37      * @param with The containing script context.
38      * @since Descripter 1.0
39      */
40     public Cases(Script<?> with) {
41         super(with);
42     }
43 
44     /**
45      * <p>Adds a key to the current <tt>Cases</tt> cache.</p>
46      * @return The current <tt>Cases</tt> cache itself.
47      * @since Descripter 1.0
48      */
49     public final Cases add(Object o) {
50         o = evaluate(o);
51         if (!map.containsKey(o)) {
52             map.put(o, next++);
53         }
54         return this;
55     }
56 
57     /**
58      * <p>Returns the index of a key by searching its reference in the current <tt>Cases</tt> 
59      * cache.</p>
60      * @return The index of a key in the current <tt>Cases</tt> cache.
61      * @since Descripter 1.0
62      */
63     public final int indexOf(Object o) {
64         o = evaluate(o);
65         return map.containsKey(o) ? map.get(o) : -1;
66     }
67 
68     /**
69      * <p>Executes the current script context.</p>
70      * <p>This method simply throws an {@link UnsupportedOperationException}.</p>
71      * @since Descripter 1.0
72      */
73     @Override
74     public final void run() {
75         throw new UnsupportedOperationException();
76     }
77 }