001/**
002 *
003 * Copyright (c) 2014, the Railo Company Ltd. All rights reserved.
004 *
005 * This library is free software; you can redistribute it and/or
006 * modify it under the terms of the GNU Lesser General Public
007 * License as published by the Free Software Foundation; either 
008 * version 2.1 of the License, or (at your option) any later version.
009 * 
010 * This library is distributed in the hope that it will be useful,
011 * but WITHOUT ANY WARRANTY; without even the implied warranty of
012 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
013 * Lesser General Public License for more details.
014 * 
015 * You should have received a copy of the GNU Lesser General Public 
016 * License along with this library.  If not, see <http://www.gnu.org/licenses/>.
017 * 
018 **/
019package lucee.runtime.type.comparator;
020
021import java.util.Comparator;
022
023import lucee.runtime.exp.ExpressionException;
024import lucee.runtime.exp.PageException;
025import lucee.runtime.exp.PageRuntimeException;
026import lucee.runtime.op.Caster;
027
028
029/**
030 * comparator implementation, compare to numbers
031 */
032public final class NumberComparator implements Comparator {
033
034        private boolean isAsc;
035
036        /**
037         * constructor of the class 
038         * @param isAsc is ascendinf or descending
039         */
040        public NumberComparator(boolean isAsc) {
041                this.isAsc=isAsc;
042        }
043        
044        @Override
045        public int compare(Object oLeft, Object oRight) {
046                try {
047                        if(isAsc) return compareObjects(oLeft, oRight);
048                        return compareObjects(oRight, oLeft);
049                } catch (PageException e) {
050                        throw new PageRuntimeException(new ExpressionException("can only sort arrays with simple values",e.getMessage()));
051                }
052        }
053        
054        private int compareObjects(Object oLeft, Object oRight) throws PageException {
055                double left=Caster.toDoubleValue(oLeft);
056                double right=Caster.toDoubleValue(oRight);
057                if(left < right)return -1;
058                return left > right ? 1 : 0;
059                
060        }
061}