Java Code Examples for jdk.nashorn.internal.runtime.JSType#toNumber()

The following examples show how to use jdk.nashorn.internal.runtime.JSType#toNumber() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: NativeDate.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
private static double[] convertCtorArgs(final Object[] args) {
    final double[] d = new double[7];
    boolean nullReturn = false;

    // should not bailout on first NaN or infinite. Need to convert all
    // subsequent args for possible side-effects via valueOf/toString overrides
    // on argument objects.
    for (int i = 0; i < d.length; i++) {
        if (i < args.length) {
            final double darg = JSType.toNumber(args[i]);
            if (isNaN(darg) || isInfinite(darg)) {
                nullReturn = true;
            }

            d[i] = (long)darg;
        } else {
            d[i] = i == 2 ? 1 : 0; // day in month defaults to 1
        }
    }

    if (0 <= d[0] && d[0] <= 99) {
        d[0] += 1900;
    }

    return nullReturn? null : d;
}
 
Example 2
Source File: NativeDate.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 6 votes vote down vote up
/**
 * ECMA B.2.5 Date.prototype.setYear (year)
 *
 * @param self self reference
 * @param year year
 * @return NativeDate
 */
@Function(attributes = Attribute.NOT_ENUMERABLE)
public static double setYear(final Object self, final Object year) {
    final NativeDate nd = getNativeDate(self);
    if (isNaN(nd.getTime())) {
        nd.setTime(utc(0, nd.getTimeZone()));
    }

    final double yearNum = JSType.toNumber(year);
    if (isNaN(yearNum)) {
        nd.setTime(NaN);
        return nd.getTime();
    }
    int yearInt = (int)yearNum;
    if (0 <= yearInt && yearInt <= 99) {
        yearInt += 1900;
    }
    setFields(nd, YEAR, new Object[] {yearInt}, true);

    return nd.getTime();
}
 
Example 3
Source File: NativeMath.java    From jdk8u_nashorn with GNU General Public License v2.0 6 votes vote down vote up
/**
 * ECMA 15.8.2.11 max(x)
 *
 * @param self  self reference
 * @param args  arguments
 *
 * @return the largest of the arguments, {@link Double#NEGATIVE_INFINITY} if no args given, or identity if one arg is given
 */
@Function(arity = 2, attributes = Attribute.NOT_ENUMERABLE, where = Where.CONSTRUCTOR)
public static double max(final Object self, final Object... args) {
    switch (args.length) {
    case 0:
        return Double.NEGATIVE_INFINITY;
    case 1:
        return JSType.toNumber(args[0]);
    default:
        double res = JSType.toNumber(args[0]);
        for (int i = 1; i < args.length; i++) {
            res = Math.max(res, JSType.toNumber(args[i]));
        }
        return res;
    }
}
 
Example 4
Source File: NativeMath.java    From openjdk-8-source with GNU General Public License v2.0 6 votes vote down vote up
/**
 * ECMA 15.8.2.11 max(x)
 *
 * @param self  self reference
 * @param args  arguments
 *
 * @return the largest of the arguments, {@link Double#NEGATIVE_INFINITY} if no args given, or identity if one arg is given
 */
@Function(arity = 2, attributes = Attribute.NOT_ENUMERABLE, where = Where.CONSTRUCTOR)
public static Object max(final Object self, final Object... args) {
    switch (args.length) {
    case 0:
        return Double.NEGATIVE_INFINITY;
    case 1:
        return JSType.toNumber(args[0]);
    default:
        double res = JSType.toNumber(args[0]);
        for (int i = 1; i < args.length; i++) {
            res = Math.max(res, JSType.toNumber(args[i]));
        }
        return res;
    }
}
 
Example 5
Source File: JavaArgumentConverters.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
@SuppressWarnings("unused")
private static Double toDouble(final Object obj0) {
    // TODO - Order tests for performance.
    for (Object obj = obj0; ;) {
        if (obj == null) {
            return null;
        } else if (obj instanceof Double) {
            return (Double) obj;
        } else if (obj instanceof Number) {
            return ((Number)obj).doubleValue();
        } else if (obj instanceof String) {
            return JSType.toNumber((String) obj);
        } else if (obj instanceof ConsString) {
            return JSType.toNumber(obj.toString());
        } else if (obj instanceof Boolean) {
            return (Boolean) obj ? 1 : +0.0;
        } else if (obj instanceof ScriptObject) {
            obj = JSType.toPrimitive(obj, Number.class);
            continue;
        } else if (obj == UNDEFINED) {
            return Double.NaN;
        }
        throw assertUnexpectedType(obj);
    }
}
 
Example 6
Source File: NativeString.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * ECMA 15.5.4.8 String.prototype.lastIndexOf (searchString, position)
 * @param self   self reference
 * @param search string to search for
 * @param pos    position to start search
 * @return last position of match or -1
 */
@Function(attributes = Attribute.NOT_ENUMERABLE, arity = 1)
public static int lastIndexOf(final Object self, final Object search, final Object pos) {

    final String str       = checkObjectToString(self);
    final String searchStr = JSType.toString(search);
    final int length       = str.length();

    int end;

    if (pos == UNDEFINED) {
        end = length;
    } else {
        final double numPos = JSType.toNumber(pos);
        end = Double.isNaN(numPos) ? length : (int)numPos;
        if (end < 0) {
            end = 0;
        } else if (end > length) {
            end = length;
        }
    }


    return str.lastIndexOf(searchStr, end);
}
 
Example 7
Source File: NativeMath.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * ECMA 15.8.2.12 min(x)
 *
 * @param self  self reference
 * @param args  arguments
 *
 * @return the smallest of the arguments, {@link Double#NEGATIVE_INFINITY} if no args given, or identity if one arg is given
 */
@Function(arity = 2, attributes = Attribute.NOT_ENUMERABLE, where = Where.CONSTRUCTOR)
public static double min(final Object self, final Object... args) {
    switch (args.length) {
    case 0:
        return Double.POSITIVE_INFINITY;
    case 1:
        return JSType.toNumber(args[0]);
    default:
        double res = JSType.toNumber(args[0]);
        for (int i = 1; i < args.length; i++) {
            res = Math.min(res, JSType.toNumber(args[i]));
        }
        return res;
    }
}
 
Example 8
Source File: NativeDate.java    From hottub with GNU General Public License v2.0 6 votes vote down vote up
/**
 * ECMA B.2.5 Date.prototype.setYear (year)
 *
 * @param self self reference
 * @param year year
 * @return NativeDate
 */
@Function(attributes = Attribute.NOT_ENUMERABLE)
public static double setYear(final Object self, final Object year) {
    final NativeDate nd = getNativeDate(self);
    if (isNaN(nd.getTime())) {
        nd.setTime(utc(0, nd.getTimeZone()));
    }

    final double yearNum = JSType.toNumber(year);
    if (isNaN(yearNum)) {
        nd.setTime(NaN);
        return nd.getTime();
    }
    int yearInt = (int)yearNum;
    if (0 <= yearInt && yearInt <= 99) {
        yearInt += 1900;
    }
    setFields(nd, YEAR, new Object[] {yearInt}, true);

    return nd.getTime();
}
 
Example 9
Source File: SparseArrayData.java    From jdk8u_nashorn with GNU General Public License v2.0 5 votes vote down vote up
@Override
public double getDouble(final int index) {
    if (index >= 0 && index < maxDenseLength) {
        return underlying.getDouble(index);
    }
    return JSType.toNumber(sparseMap.get(indexToKey(index)));
}
 
Example 10
Source File: SparseArrayData.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
@Override
public double getDouble(final int index) {
    if (index >= 0 && index < maxDenseLength) {
        return underlying.getDouble(index);
    }
    return JSType.toNumber(sparseMap.get(indexToKey(index)));
}
 
Example 11
Source File: LengthNotWritableFilter.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
@Override
public double getDouble(final int index) {
    if (index >= length()) {
        return JSType.toNumber(get(index));
    }
    return underlying.getDouble(index);
}
 
Example 12
Source File: NativeMath.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
/**
 * ECMA 15.8.2.15 round(x)
 *
 * @param self  self reference
 * @param x     argument
 *
 * @return x rounded
 */
@Function(attributes = Attribute.NOT_ENUMERABLE, where = Where.CONSTRUCTOR)
public static double round(final Object self, final Object x) {
    final double d = JSType.toNumber(x);
    if (Math.getExponent(d) >= 52) {
        return d;
    }
    return Math.copySign(Math.floor(d + 0.5), d);
}
 
Example 13
Source File: NativeArray.java    From openjdk-8 with GNU General Public License v2.0 5 votes vote down vote up
static long validLength(final Object length, final boolean reject) {
    final double doubleLength = JSType.toNumber(length);
    if (!Double.isNaN(doubleLength) && JSType.isRepresentableAsLong(doubleLength)) {
        final long len = (long) doubleLength;
        if (len >= 0 && len <= JSType.MAX_UINT) {
            return len;
        }
    }
    if (reject) {
        throw rangeError("inappropriate.array.length", ScriptRuntime.safeToString(length));
    }
    return -1;
}
 
Example 14
Source File: NativeJSAdapter.java    From openjdk-8 with GNU General Public License v2.0 4 votes vote down vote up
private double callAdapteeDouble(final String name, final Object... args) {
    return JSType.toNumber(callAdaptee(name, args));
}
 
Example 15
Source File: NativeJSON.java    From jdk8u60 with GNU General Public License v2.0 4 votes vote down vote up
/**
 * ECMA 15.12.3 stringify ( value [ , replacer [ , space ] ] )
 *
 * @param self     self reference
 * @param value    ECMA script value (usually object or array)
 * @param replacer either a function or an array of strings and numbers
 * @param space    optional parameter - allows result to have whitespace injection
 *
 * @return a string in JSON format
 */
@Function(attributes = Attribute.NOT_ENUMERABLE, where = Where.CONSTRUCTOR)
public static Object stringify(final Object self, final Object value, final Object replacer, final Object space) {
    // The stringify method takes a value and an optional replacer, and an optional
    // space parameter, and returns a JSON text. The replacer can be a function
    // that can replace values, or an array of strings that will select the keys.

    // A default replacer method can be provided. Use of the space parameter can
    // produce text that is more easily readable.

    final StringifyState state = new StringifyState();

    // If there is a replacer, it must be a function or an array.
    if (replacer instanceof ScriptFunction) {
        state.replacerFunction = (ScriptFunction) replacer;
    } else if (isArray(replacer) ||
            replacer instanceof Iterable ||
            (replacer != null && replacer.getClass().isArray())) {

        state.propertyList = new ArrayList<>();

        final Iterator<Object> iter = ArrayLikeIterator.arrayLikeIterator(replacer);

        while (iter.hasNext()) {
            String item = null;
            final Object v = iter.next();

            if (v instanceof String) {
                item = (String) v;
            } else if (v instanceof ConsString) {
                item = v.toString();
            } else if (v instanceof Number ||
                    v instanceof NativeNumber ||
                    v instanceof NativeString) {
                item = JSType.toString(v);
            }

            if (item != null) {
                state.propertyList.add(item);
            }
        }
    }

    // If the space parameter is a number, make an indent
    // string containing that many spaces.

    String gap;

    // modifiable 'space' - parameter is final
    Object modSpace = space;
    if (modSpace instanceof NativeNumber) {
        modSpace = JSType.toNumber(JSType.toPrimitive(modSpace, Number.class));
    } else if (modSpace instanceof NativeString) {
        modSpace = JSType.toString(JSType.toPrimitive(modSpace, String.class));
    }

    if (modSpace instanceof Number) {
        final int indent = Math.min(10, JSType.toInteger(modSpace));
        if (indent < 1) {
            gap = "";
        } else {
            final StringBuilder sb = new StringBuilder();
            for (int i = 0; i < indent; i++) {
                sb.append(' ');
            }
            gap = sb.toString();
        }
    } else if (JSType.isString(modSpace)) {
        final String str = modSpace.toString();
        gap = str.substring(0, Math.min(10, str.length()));
    } else {
        gap = "";
    }

    state.gap = gap;

    final ScriptObject wrapper = Global.newEmptyInstance();
    wrapper.set("", value, 0);

    return str("", wrapper, state);
}
 
Example 16
Source File: NativeString.java    From nashorn with GNU General Public License v2.0 4 votes vote down vote up
@Override
public double getDouble(final int key) {
    return JSType.toNumber(get(key));
}
 
Example 17
Source File: LiteralNode.java    From openjdk-8 with GNU General Public License v2.0 2 votes vote down vote up
/**
 * Fetch double value of node.
 *
 * @return double value of node.
 */
public double getNumber() {
    return JSType.toNumber(value);
}
 
Example 18
Source File: AbstractJSObject.java    From jdk8u_nashorn with GNU General Public License v2.0 2 votes vote down vote up
/**
 * Returns this object's numeric value.
 *
 * @return this object's numeric value.
 * @deprecated use {@link #getDefaultValue(Class)} with {@link Number} hint instead.
 */
@Override @Deprecated
public double toNumber() {
    return JSType.toNumber(JSType.toPrimitive(this, Number.class));
}
 
Example 19
Source File: LiteralNode.java    From hottub with GNU General Public License v2.0 2 votes vote down vote up
/**
 * Fetch double value of node.
 *
 * @return double value of node.
 */
public double getNumber() {
    return JSType.toNumber(value);
}
 
Example 20
Source File: LiteralNode.java    From nashorn with GNU General Public License v2.0 2 votes vote down vote up
/**
 * Fetch double value of node.
 *
 * @return double value of node.
 */
public double getNumber() {
    return JSType.toNumber(value);
}