Skip to content

Commit

Permalink
use Number namespace
Browse files Browse the repository at this point in the history
  • Loading branch information
jaskfla committed Jun 20, 2024
1 parent 0c26dd8 commit 58a059c
Show file tree
Hide file tree
Showing 43 changed files with 124 additions and 160 deletions.
Original file line number Diff line number Diff line change
@@ -1,11 +1,9 @@
/*
* Tupaia
* Copyright (c) 2017 - 2021 Beyond Essential Systems Pty Ltd
*
*/

import { Request } from 'express';

import { Route } from '@tupaia/server-boilerplate';

export type FetchHierarchyEntitiesRequest = Request<
Expand Down Expand Up @@ -48,7 +46,7 @@ export class FetchHierarchyEntitiesRoute extends Route<FetchHierarchyEntitiesReq

// If pageSize is provided, return only the first n entities
if (pageSize) {
return flattenedDescendants.slice(0, parseInt(pageSize, 10));
return flattenedDescendants.slice(0, Number.parseInt(pageSize, 10));
}
return flattenedDescendants;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ export const DateRangeField = () => {
new Date(date.setMinutes(date.getMinutes() - date.getTimezoneOffset()));

const convertDateToIsoString = date => {
if (!date || isNaN(new Date(date).getTime())) return null;
if (!date || Number.isNaN(new Date(date).getTime())) return null;
const correctedDate = shiftEpoch(date);

// Slice to discard timestamp, keeping only "yyyy-mm-dd"
Expand Down
4 changes: 2 additions & 2 deletions packages/admin-panel/src/table/actions.js
Original file line number Diff line number Diff line change
Expand Up @@ -112,8 +112,8 @@ const refreshDataWithDebounce = debounce(
};
const response = await api.get(endpoint, queryParameters);
const linkHeader = parseLinkHeader(response.headers.get('Link'));
const totalRecords = parseInt(response.headers.get('X-Total-Count'), 10);
const lastPageNumber = parseInt(linkHeader.last.page, 10);
const totalRecords = Number.parseInt(response.headers.get('X-Total-Count'), 10);
const lastPageNumber = Number.parseInt(linkHeader.last.page, 10);

dispatch({
type: DATA_FETCH_SUCCESS,
Expand Down
4 changes: 2 additions & 2 deletions packages/central-server/src/hooks/utilities.js
Original file line number Diff line number Diff line change
Expand Up @@ -28,8 +28,8 @@ export async function getHookAnswerValues(surveyResponse, baseHookName, defaultF

export function parseCoordinates(answerText) {
const { latitude, longitude } = JSON.parse(answerText);
if (Number.isNaN(parseFloat(latitude)) || Number.isNaN(parseFloat(longitude))) {
throw new Error(`Invalid coordinate data: ${answer.text}`);
if (Number.isNaN(Number.parseFloat(latitude)) || Number.isNaN(Number.parseFloat(longitude))) {
throw new Error(`Invalid coordinate data: ${answerText}`);
}

return { latitude, longitude };
Expand Down
6 changes: 3 additions & 3 deletions packages/database/src/TupaiaDatabase.js
Original file line number Diff line number Diff line change
Expand Up @@ -102,8 +102,8 @@ export class TupaiaDatabase {
pgTypes.setTypeParser(pgTypes.builtins.TIMESTAMP, val => val);

if (useNumericStuff) {
pgTypes.setTypeParser(pgTypes.builtins.NUMERIC, parseFloat);
pgTypes.setTypeParser(20, parseInt); // bigInt type to Integer
pgTypes.setTypeParser(pgTypes.builtins.NUMERIC, Number.parseFloat);
pgTypes.setTypeParser(20, Number.parseInt); // bigInt type to Integer
}
}

Expand Down Expand Up @@ -319,7 +319,7 @@ export class TupaiaDatabase {
async count(recordType, where, options) {
// If just a simple query without options, use the more efficient knex count method
const result = await this.find(recordType, where, options, QUERY_METHODS.COUNT);
return parseInt(result[0].count, 10);
return Number.parseInt(result[0].count, 10);
}

async create(recordType, record, where) {
Expand Down
2 changes: 1 addition & 1 deletion packages/database/src/modelClasses/DataServiceSyncGroup.js
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ export class DataServiceSyncGroupRecord extends DatabaseRecord {
[this.id],
);

return parseInt(count);
return Number.parseInt(count);
}

async getLatestLogs(limit = 100, offset = 0) {
Expand Down
2 changes: 1 addition & 1 deletion packages/database/src/runPostMigration.js
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ export const runPostMigration = async driver => {
const { rows: postgisExtension } = await driver.runSql(`
SELECT COUNT(1) FROM pg_extension WHERE extname = 'postgis';
`);
if (!parseInt(postgisExtension[0].count, 10)) {
if (!Number.parseInt(postgisExtension[0].count, 10)) {
throw new Error(
"PostGIS extension is required. Install the binaries and run 'CREATE EXTENSION postgis;' in postgres to install it.",
);
Expand Down
4 changes: 2 additions & 2 deletions packages/datatrak-web-server/src/routes/ActivityFeedRoute.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import { Request } from 'express';
import camelcaseKeys from 'camelcase-keys';
import { Route } from '@tupaia/server-boilerplate';
import { DatatrakWebActivityFeedRequest, FeedItemTypes } from '@tupaia/types';
import { JOIN_TYPES, RECORDS, QUERY_CONJUNCTIONS } from '@tupaia/database';
import { JOIN_TYPES, QUERY_CONJUNCTIONS, RECORDS } from '@tupaia/database';

export type ActivityFeedRequest = Request<
DatatrakWebActivityFeedRequest.Params,
Expand Down Expand Up @@ -54,7 +54,7 @@ export class ActivityFeedRoute extends Route<ActivityFeedRequest> {
const { query, models, accessPolicy } = this.req;
const { page: queryPage, projectId } = query;

const page = queryPage ? parseInt(queryPage, 10) : 0;
const page = queryPage ? Number.parseInt(queryPage, 10) : 0;

const pinned = page === 0 ? await this.getPinnedItem() : undefined;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ export const LatLongFields = ({
const handleChange = (e: ChangeEvent<{}>, field: string) => {
setGeolocation({
...geolocation,
[field]: parseFloat((e.target as HTMLInputElement).value),
[field]: Number.parseFloat((e.target as HTMLInputElement).value),
accuracy: 'N/A',
});
};
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import React from 'react';
import styled from 'styled-components';
import { LatLngLiteral } from 'leaflet';
import { MapContainer as BaseMapContainer, ZoomControl } from 'react-leaflet';
import { TilePicker, DEFAULT_TILESETS } from '@tupaia/ui-map-components';
import { DEFAULT_TILESETS, TilePicker } from '@tupaia/ui-map-components';
import { DEFAULT_BOUNDS, DEFAULT_ZOOM_LEVEL, UNSET_LOCATION_ZOOM_LEVEL } from './constants';
import { UserLocationMap } from './UserLocationMap';
import { PinDrop } from './PinDrop';
Expand Down Expand Up @@ -79,8 +79,8 @@ export const Map = ({ lat, lng, setCoordinates, tileSet, onChangeTileSet }: MapP
// round coordinates to 4 decimal places before setting them - any less and the coordinates are not very accurate
const onUpdateCoordinates = ({ lat, lng }: LatLngLiteral) => {
setCoordinates({
lat: parseFloat(lat.toFixed(4)),
lng: parseFloat(lng.toFixed(4)),
lat: Number.parseFloat(lat.toFixed(4)),
lng: Number.parseFloat(lng.toFixed(4)),
});
};
return (
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ export const SurveyFormDispatchContext = createContext<Dispatch<SurveyFormAction
export const SurveyContext = ({ children }) => {
const [state, dispatch] = useReducer(surveyReducer, defaultContext);
const { surveyCode, ...params } = useParams<SurveyParams>();
const screenNumber = params.screenNumber ? parseInt(params.screenNumber!, 10) : null;
const screenNumber = params.screenNumber ? Number.parseInt(params.screenNumber!, 10) : null;
const { data: survey } = useSurvey(surveyCode);
const isResponseScreen = !!useMatch(ROUTES.SURVEY_RESPONSE);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -108,7 +108,7 @@ const getArithmeticDependantAnswer = (questionId, answer, valueTranslation, defa
}
// return raw answer if it's a number, else 0 (e.g. if no valueTranslation provided for the question and this specific answer when answer is non-numeric)
if (answer !== undefined && answer !== null && answer !== '') {
return isNaN(answer) ? 0 : answer; // return raw answer
return Number.isNaN(answer) ? 0 : answer; // return raw answer
}

return defaultValues[questionId] !== undefined ? defaultValues[questionId] : 0; // No answer found, return the default answer
Expand Down Expand Up @@ -139,7 +139,7 @@ const getArithmeticResult = (
// Evaluate the expression
expressionParser.setAll(values);

const result = !isNaN(expressionParser.evaluate(formula))
const result = !Number.isNaN(expressionParser.evaluate(formula))
? Math.round(expressionParser.evaluate(formula) * 1000) / 1000 // Round to 3 decimal places
: 0;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import { getAllSurveyComponents, useSurveyForm } from '.';

const transformNumberValue = (value: string | number, originalValue: string | number) => {
// This is a workaround for yup not handling empty number fields (https://github.com/jquense/yup/issues/298)
return originalValue === '' || isNaN(originalValue as number) ? null : value;
return originalValue === '' || Number.isNaN(originalValue as number) ? null : value;
};

const getBaseSchema = (type: QuestionType) => {
Expand Down Expand Up @@ -76,7 +76,7 @@ const getValidationSchema = (screenComponents?: SurveyScreenComponent[]) => {
// Show the required message when the user has not entered a location at all
if (
(!value?.latitude && !value?.longitude) ||
(isNaN(value.latitude) && isNaN(value.longitude))
(Number.isNaN(value.latitude) && Number.isNaN(value.longitude))
)
return 'Required';
// Otherwise show the invalid location message
Expand All @@ -85,8 +85,8 @@ const getValidationSchema = (screenComponents?: SurveyScreenComponent[]) => {
value =>
value?.latitude &&
value?.longitude &&
!isNaN(value.latitude) &&
!isNaN(value.longitude),
!Number.isNaN(value.latitude) &&
!Number.isNaN(value.longitude),
);
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ const formatComparisonValue = (value: Value, operator: Operator) => {
};

const formatValue = <T extends keyof EntityFilterQuery>(field: T, value: string) =>
isNumericField(field) ? parseFloat(value) : value;
isNumericField(field) ? Number.parseFloat(value) : value;

const convertValueToAdvancedCriteria = (
field: keyof EntityFilterQuery,
Expand Down
2 changes: 1 addition & 1 deletion packages/lesmis/src/components/YearSelector.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import { MIN_DATA_YEAR } from '../constants';
const getYearOptions = () => {
const years = [];

const startYear = parseInt(MIN_DATA_YEAR);
const startYear = Number.parseInt(MIN_DATA_YEAR);
let year = new Date().getFullYear();

while (year >= startYear) {
Expand Down
6 changes: 3 additions & 3 deletions packages/meditrak-app-server/src/routes/SocialFeedRoute.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
import { Request } from 'express';
import { QUERY_CONJUNCTIONS } from '@tupaia/database';
import { Route } from '@tupaia/server-boilerplate';
import { NullableKeysToOptional, FeedItem } from '@tupaia/types';
import { FeedItem, NullableKeysToOptional } from '@tupaia/types';

const DEFAULT_NUMBER_PER_PAGE = 20;

Expand Down Expand Up @@ -75,9 +75,9 @@ export class SocialFeedRoute extends Route<SocialFeedRequest> {
page: queryPage,
numberPerPage: queryNumberPerPage,
} = query;
const pageNumber = queryPage ? parseInt(queryPage, 10) : 0;
const pageNumber = queryPage ? Number.parseInt(queryPage, 10) : 0;
const numberPerPage = queryNumberPerPage
? parseInt(queryNumberPerPage, 10)
? Number.parseInt(queryNumberPerPage, 10)
: DEFAULT_NUMBER_PER_PAGE;

// @todo: Use user access policy to determine the type of information appearing in the feed.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ export class ChangesMetadataRoute extends Route<ChangesMetadataRequest> {
>(this.req, 'count(*)');

const queryResult = await query.executeOnDatabase(this.req.models.database);
const changeCount = parseInt(queryResult[0].count);
const changeCount = Number.parseInt(queryResult[0].count);

return { changeCount, countries, permissionGroups };
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ export class CountChangesRoute extends Route<CountChangesRequest> {
// Uses non-permissions based sync, since permissions based sync uses /changes/metadata route instead
const { query } = await buildMeditrakSyncQuery<{ count: string }[]>(this.req, 'count(*)');
const queryResult = await query.executeOnDatabase(this.req.models.database);
const changeCount = parseInt(queryResult[0].count);
const changeCount = Number.parseInt(queryResult[0].count);

return { changeCount };
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -57,9 +57,9 @@ export const extractSinceValue = (req: Request) => {

if (typeof since === 'number') return since;

const parsedSince = parseFloat(since as string);
const parsedSince = Number.parseFloat(since as string);

if (isNaN(parsedSince)) {
if (Number.isNaN(parsedSince)) {
throw new ValidationError("The 'since' parameter must be a number.");
}

Expand Down
Loading

0 comments on commit 58a059c

Please sign in to comment.