pip-services3-commons-node
Version:
Portable abstractions and patterns for Pip.Services in Node.js
61 lines (55 loc) • 2.21 kB
text/typescript
/** @module convert */
/** @hidden */
let _ = require('lodash');
import { LongConverter } from './LongConverter';
/**
* Converts arbitrary values into integers using extended conversion rules:
* - Strings are converted to floats, then to integers
* - DateTime: total number of milliseconds since unix epoсh
* - Boolean: 1 for true and 0 for false
*
* ### Example ###
*
* let value1 = IntegerConverter.toNullableInteger("ABC"); // Result: null
* let value2 = IntegerConverter.toNullableInteger("123.456"); // Result: 123
* let value3 = IntegerConverter.toNullableInteger(true); // Result: 1
* let value4 = IntegerConverter.toNullableInteger(new Date()); // Result: current milliseconds
*/
export class IntegerConverter {
/**
* Converts value into integer or returns null when conversion is not possible.
*
* @param value the value to convert.
* @returns integer value or null when conversion is not supported.
*
* @see [[LongConverter.toNullableLong]]
*/
public static toNullableInteger(value: any): number {
return LongConverter.toNullableLong(value);
}
/**
* Converts value into integer or returns 0 when conversion is not possible.
*
* @param value the value to convert.
* @returns integer value or 0 when conversion is not supported.
*
* @see [[LongConverter.toLong]]
* @see [[LongConverter.toLongWithDefault]]
*/
public static toInteger(value: any): number {
return LongConverter.toLong(value);
}
/**
* Converts value into integer or returns default value when conversion is not possible.
*
* @param value the value to convert.
* @param defaultValue the default value.
* @returns integer value or default when conversion is not supported.
*
* @see [[LongConverter.toLongWithDefault]]
* @see [[LongConverter.toNullableLong]]
*/
public static toIntegerWithDefault(value: any, defaultValue: number): number {
return LongConverter.toLongWithDefault(value, defaultValue);
}
}