Skip to content

Commit

Permalink
refactor: convert helpers to TS
Browse files Browse the repository at this point in the history
  • Loading branch information
Niloofar Sadeghi committed Oct 9, 2022
1 parent b556e43 commit 40354ee
Show file tree
Hide file tree
Showing 24 changed files with 527 additions and 308 deletions.
77 changes: 77 additions & 0 deletions packages/shared/src/utils/contract/contract-types.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
import { ContractUpdate } from '@deriv/api-types';

export type TStatus = 'open' | 'sold' | 'won' | 'lost' | 'cancelled';

export type TGetFinalPrice = {
sell_price: number;
bid_price: number;
};

export type TIsEnded = Partial<TGetFinalPrice> & {
is_valid_to_sell?: 0 | 1;
status?: TStatus;
is_expired?: 0 | 1;
is_settleable?: 0 | 1;
};

export type TContractInfo = {
tick_stream?: TTickItem[];
cancellation?: {
ask_price?: number;
date_expiry?: number;
};
status?: TStatus;
is_expired?: 0 | 1;
is_settleable?: 0 | 1;
is_valid_to_cancel?: 0 | 1;
entry_spot?: number;
profit?: number;
entry_tick_time?: number;
entry_tick?: number;
current_spot_time?: number;
current_spot?: number;
barrier?: string;
contract_type?: string;
exit_tick_time?: number;
date_expiry?: number;
is_path_dependent?: 0 | 1;
sell_time?: number | null;
tick_count?: number;
date_start?: number;
is_forward_starting?: 0 | 1;
};

export type TIsValidToSell = TIsEnded & {
is_valid_to_sell: 0 | 1;
};

export type TTickItem = {
epoch?: number;
tick?: null | number;
tick_display_value?: null | string;
};

export type TDigitsInfo = { [key: number]: { digit: number; spot: string } };

export type TGetTotalProfit = {
bid_price: number;
buy_price: number;
};

type TLimitProperty = {
display_name?: string;
order_amount?: null | number;
order_date?: number;
value?: null | string;
};

export type TLimitOrder = Partial<Record<'stop_loss' | 'stop_out' | 'take_profit', TLimitProperty>>;

export type TGetDisplayStatus = TGetTotalProfit & {
status: TStatus;
};

export type TGetContractUpdateConfig = {
contract_update: ContractUpdate;
limit_order: TLimitOrder;
};
Original file line number Diff line number Diff line change
@@ -1,55 +1,60 @@
import moment from 'moment';
import 'moment/min/locales';

type TExtendedMoment = typeof moment & {
createFromInputFallback: (config: { _d: Date }) => void;
};

// Disables moment's fallback to native Date object
// moment will return `Invalid Date` if date cannot be parsed
moment.createFromInputFallback = function (config) {
(moment as TExtendedMoment).createFromInputFallback = function (config) {
config._d = new Date(NaN); // eslint-disable-line no-underscore-dangle
};

// Localize moment instance with specific object
export const initMoment = lang => moment.locale(lang);
export const initMoment = (lang: string) => moment.locale(lang);

/**
* Convert epoch to moment object
* @param {Number} epoch
* @return {moment} the moment object of provided epoch
*/
export const epochToMoment = epoch => moment.unix(epoch).utc();
export const epochToMoment = (epoch: number) => moment.unix(epoch).utc();

/**
* Convert date string or epoch to moment object
* @param {Number} value the date in epoch format
* @param {String} value the date in string format
* @return {moment} the moment object of 'now' or the provided date epoch or string
*/
export const toMoment = value => {
export const toMoment = (value?: moment.MomentInput): moment.Moment => {
if (!value) return moment().utc(); // returns 'now' moment object
if (value instanceof moment && value.isValid() && value.isUTC()) return value; // returns if already a moment object
if (value instanceof moment && (value as moment.Moment).isValid() && (value as moment.Moment).isUTC())
return value as moment.Moment; // returns if already a moment object
if (typeof value === 'number') return epochToMoment(value); // returns epochToMoment() if not a date

if (/invalid/i.test(moment(value))) {
if (/invalid/i.test(moment(value).toString())) {
const today_moment = moment();
return value > today_moment.utc().daysInMonth()
? moment.utc(today_moment.add(value, 'd'), 'DD MMM YYYY')
? moment.utc(today_moment.add(value as string | number, 'd'), 'DD MMM YYYY')
: moment.utc(value, 'DD MMM YYYY'); // returns target date
}
return moment.utc(value);
};

export const toLocalFormat = time => moment.utc(time).local().format('YYYY-MM-DD HH:mm:ss Z');
export const toLocalFormat = (time: moment.MomentInput) => moment.utc(time).local().format('YYYY-MM-DD HH:mm:ss Z');
/**
* Set specified time on moment object
* @param {moment} moment_obj the moment to set the time on
* @param {String} time 24 hours format, may or may not include seconds
* @return {moment} a new moment object of result
*/
export const setTime = (moment_obj, time) => {
export const setTime = (moment_obj: moment.Moment, time: string) => {
const [hour, minute, second] = time ? time.split(':') : [0, 0, 0];
moment_obj
.hour(hour)
.minute(minute || 0)
.second(second || 0);
.hour(+hour)
.minute(+minute || 0)
.second(+second || 0);
return moment_obj;
};

Expand All @@ -59,23 +64,24 @@ export const setTime = (moment_obj, time) => {
* @param {String} time the time to set on the date
* @return {Number} unix value of the result
*/
export const convertToUnix = (epoch, time) => setTime(toMoment(epoch), time).unix();
export const convertToUnix = (epoch: number | string, time: string) => setTime(toMoment(epoch), time).unix();

export const toGMTFormat = time =>
export const toGMTFormat = (time?: moment.MomentInput) =>
moment(time || undefined)
.utc()
.format('YYYY-MM-DD HH:mm:ss [GMT]');

export const formatDate = (date, date_format = 'YYYY-MM-DD') => toMoment(date).format(date_format);
export const formatDate = (date?: moment.MomentInput, date_format = 'YYYY-MM-DD') => toMoment(date).format(date_format);

export const formatTime = (epoch, time_format = 'HH:mm:ss [GMT]') => toMoment(epoch).format(time_format);
export const formatTime = (epoch: number | string, time_format = 'HH:mm:ss [GMT]') =>
toMoment(epoch).format(time_format);

/**
* return the number of days from today to date specified
* @param {String} date the date to calculate number of days from today
* @return {Number} an integer of the number of days
*/
export const daysFromTodayTo = date => {
export const daysFromTodayTo = (date?: string) => {
const diff = toMoment(date).startOf('day').diff(toMoment().startOf('day'), 'days');
return !date || diff < 0 ? '' : diff;
};
Expand All @@ -85,26 +91,30 @@ export const daysFromTodayTo = date => {
* @param {String} date the date to calculate number of days since
* @return {Number} an integer of the number of days
*/
export const daysSince = date => {
export const daysSince = (date: string) => {
const diff = toMoment().startOf('day').diff(toMoment(date).startOf('day'), 'days');
return !date ? '' : diff;
};

/**
* return the number of months between two specified dates
*/
export const diffInMonths = (now, then) => then.diff(now, 'month');
export const diffInMonths = (now: moment.MomentInput, then: moment.Moment) => then.diff(now, 'month');
/**
* return moment duration between two dates
* @param {Number} epoch start time
* @param {Number} epoch end time
* @return {moment.duration} moment duration between start time and end time
*/
export const getDiffDuration = (start_time, end_time) =>
export const getDiffDuration = (start_time: number, end_time: number) =>
moment.duration(moment.unix(end_time).diff(moment.unix(start_time)));

/** returns the DD MM YYYY format */
export const getDateFromNow = (days, unit, format) => {
export const getDateFromNow = (
days: string | number,
unit?: moment.unitOfTime.DurationConstructor,
format?: string
) => {
const date = moment(new Date());
return date.add(days, unit).format(format);
};
Expand All @@ -114,7 +124,7 @@ export const getDateFromNow = (days, unit, format) => {
* @param {moment.duration} moment duration object
* @return {String} formatted display string
*/
export const formatDuration = (duration, format) => {
export const formatDuration = (duration: moment.Duration, format?: string) => {
const d = Math.floor(duration.asDays()); // duration.days() does not include months/years
const h = duration.hours();
const m = duration.minutes();
Expand All @@ -135,95 +145,99 @@ export const formatDuration = (duration, format) => {
* return true if the time_str is in "HH:MM" format, else return false
* @param {String} time_str time
*/
export const isTimeValid = time_str =>
export const isTimeValid = (time_str: string) =>
/^([0-9]|[0-1][0-9]|2[0-3]):([0-9]|[0-5][0-9])(:([0-9]|[0-5][0-9]))?$/.test(time_str);

/**
* return true if the time_str's hour is between 0 and 23, else return false
* @param {String} time_str time
*/
export const isHourValid = time_str => isTimeValid(time_str) && /^([01][0-9]|2[0-3])$/.test(time_str.split(':')[0]);
export const isHourValid = (time_str: string) =>
isTimeValid(time_str) && /^([01][0-9]|2[0-3])$/.test(time_str.split(':')[0]);

/**
* return true if the time_str's minute is between 0 and 59, else return false
* @param {String} time_str time
*/
export const isMinuteValid = time_str => isTimeValid(time_str) && /^[0-5][0-9]$/.test(time_str.split(':')[1]);
export const isMinuteValid = (time_str: string) => isTimeValid(time_str) && /^[0-5][0-9]$/.test(time_str.split(':')[1]);

/**
* return true if the date is typeof string and a valid moment date, else return false
* @param {String|moment} date date
*/
export const isDateValid = date => moment(date, 'DD MMM YYYY').isValid();
export const isDateValid = (date: moment.MomentInput) => moment(date, 'DD MMM YYYY').isValid();

/**
* add the specified number of days to the given date
* @param {String} date date
* @param {Number} num_of_days number of days to add
*/
export const addDays = (date, num_of_days) => toMoment(date).clone().add(num_of_days, 'day');
export const addDays = (date: string, num_of_days: number) => toMoment(date).clone().add(num_of_days, 'day');

/**
* add the specified number of weeks to the given date
* @param {String} date date
* @param {Number} num_of_weeks number of days to add
*/
export const addWeeks = (date, num_of_weeks) => toMoment(date).clone().add(num_of_weeks, 'week');
export const addWeeks = (date: string, num_of_weeks: number) => toMoment(date).clone().add(num_of_weeks, 'week');

/**
* add the specified number of months to the given date
* @param {String} date date
* @param {Number} num_of_months number of months to add
*/
export const addMonths = (date, num_of_months) => toMoment(date).clone().add(num_of_months, 'month');
export const addMonths = (date: string, num_of_months: number) => toMoment(date).clone().add(num_of_months, 'month');

/**
* add the specified number of years to the given date
* @param {String} date date
* @param {Number} num_of_years number of years to add
*/
export const addYears = (date, num_of_years) => toMoment(date).clone().add(num_of_years, 'year');
export const addYears = (date: string, num_of_years: number) => toMoment(date).clone().add(num_of_years, 'year');

/**
* subtract the specified number of days from the given date
* @param {String} date date
* @param {Number} num_of_days number of days to subtract
*/
export const subDays = (date, num_of_days) => toMoment(date).clone().subtract(num_of_days, 'day');
export const subDays = (date: string, num_of_days: number) => toMoment(date).clone().subtract(num_of_days, 'day');

/**
* subtract the specified number of months from the given date
* @param {String} date date
* @param {Number} num_of_months number of months to subtract
*/
export const subMonths = (date, num_of_months) => toMoment(date).clone().subtract(num_of_months, 'month');
export const subMonths = (date: string, num_of_months: number) =>
toMoment(date).clone().subtract(num_of_months, 'month');

/**
* subtract the specified number of years from the given date
* @param {String} date date
* @param {Number} num_of_years number of years to subtract
*/
export const subYears = (date, num_of_years) => toMoment(date).clone().subtract(num_of_years, 'year');
export const subYears = (date: string, num_of_years: number) => toMoment(date).clone().subtract(num_of_years, 'year');

/**
* returns the minimum moment between the two passing parameters
* @param {moment|string|epoch} first datetime parameter
* @param {moment|string|epoch} second datetime parameter
*/
export const minDate = (date_1, date_2) => moment.min(toMoment(date_1), toMoment(date_2));
export const minDate = (date_1: moment.MomentInput, date_2: moment.MomentInput) =>
moment.min(toMoment(date_1), toMoment(date_2));

/**
* returns a new date
* @param {moment|string|epoch} date date
*/
export const getStartOfMonth = date => toMoment(date).clone().startOf('month').format('YYYY-MM-DD');
export const getStartOfMonth = (date: moment.MomentInput) =>
toMoment(date).clone().startOf('month').format('YYYY-MM-DD');

/**
* returns miliseconds into UTC formatted string
* @param {Number} miliseconds miliseconds
* @param {String} str_format formatting using moment e.g - YYYY-MM-DD HH:mm
*/
export const formatMilliseconds = (miliseconds, str_format, is_local_time = false) => {
export const formatMilliseconds = (miliseconds: moment.MomentInput, str_format: string, is_local_time = false) => {
if (is_local_time) {
return moment(miliseconds).format(str_format);
}
Expand All @@ -236,19 +250,19 @@ export const formatMilliseconds = (miliseconds, str_format, is_local_time = fals
* @param {String} from_date_format initial date format
* @param {String} to_date_format to date format
*/
export const convertDateFormat = (date, from_date_format, to_date_format) =>
export const convertDateFormat = (date: moment.MomentInput, from_date_format: string, to_date_format: string) =>
moment(date, from_date_format).format(to_date_format);

/**
* Convert 24 hours format time to 12 hours formatted time.
* @param {String} time 24 hours format, may or may not include seconds
* @return {String} equivalent 12-hour time
*/
export const convertTimeFormat = time => {
export const convertTimeFormat = (time: string) => {
const time_moment_obj = moment(time, 'HH:mm');
const time_hour = time_moment_obj.format('HH');
const time_min = time_moment_obj.format('mm');
const formatted_time = `${Number(time_hour % 12) || 12}:${time_min}`;
const time_suffix = `${Number(time_hour >= 12) ? 'pm' : 'am'}`;
const formatted_time = `${Number(time_hour) % 12 || 12}:${time_min}`;
const time_suffix = `${Number(time_hour) >= 12 ? 'pm' : 'am'}`;
return `${formatted_time} ${time_suffix}`;
};
Original file line number Diff line number Diff line change
Expand Up @@ -48,9 +48,9 @@ describe('buildBarriersConfig', () => {
const contract = {
...contract_obj,
barriers: 1,
low_barrier: 22,
barrier: 33,
high_barrier: 44,
low_barrier: '22',
barrier: '33',
high_barrier: '44',
};
expect(buildBarriersConfig(contract)).to.eql({
count: 1,
Expand All @@ -66,8 +66,8 @@ describe('buildBarriersConfig', () => {
const contract = {
...contract_obj,
barriers: 1,
low_barrier: 22,
barrier: 33,
low_barrier: '22',
barrier: '33',
};
expect(buildBarriersConfig(contract)).to.eql({
count: 1,
Expand Down
Loading

0 comments on commit 40354ee

Please sign in to comment.