Skip to content

TagSpaces is an offline, open source, document manager with tagging support

fixing ts issues

Ilian Sapundshiev81941a77f337
diff --git a/app/components/Search.tsx b/app/components/Search.tsx
index f34733193..9e7c269c7 100644
--- a/app/components/Search.tsx
+++ b/app/components/Search.tsx
@@ -1,4 +1,3 @@
-// @ts-nocheck
/**
* TagSpaces - universal file and folder organizer
* Copyright (C) 2017-present TagSpaces UG (haftungsbeschraenkt)
@@ -100,12 +99,13 @@ interface State {
tagPlaceRadius: number;
fileSize: string;
searchMenuOpened: boolean;
- searchMenuAnchorEl: Element;
+ searchMenuAnchorEl: Element | null;
}
const olc = {}; // new openlocationcode();
class Search extends React.Component<Props, State> {
+ // @ts-ignore
state = {
textQuery: '',
tagsAND: [],
@@ -135,6 +135,7 @@ class Search extends React.Component<Props, State> {
const name = target.name;
this.setState(
+ // @ts-ignore
{
[name]: value
},
@@ -143,6 +144,7 @@ class Search extends React.Component<Props, State> {
};
handleTagFieldChange = (name, value) => {
+ // @ts-ignore
this.setState({ [name]: value }, this.executeSearch);
};
@@ -178,9 +180,9 @@ class Search extends React.Component<Props, State> {
let tagPlaceHelper;
if (isPlusCode(value)) {
- const coord = olc.decode(value);
- lat = Number(coord.latitudeCenter.toFixed(7));
- lon = Number(coord.longitudeCenter.toFixed(7));
+ // const coord = olc.decode(value);
+ // lat = Number(coord.latitudeCenter.toFixed(7));
+ // lon = Number(coord.longitudeCenter.toFixed(7));
} else {
const latLon = parseLatLon(value);
if (latLon) {
@@ -269,6 +271,7 @@ class Search extends React.Component<Props, State> {
tagsAND: this.state.tagsAND,
tagsOR: this.state.tagsOR,
tagsNOT: this.state.tagsNOT,
+ // @ts-ignore
searchBoxing: this.state.searchBoxing,
fileTypes: this.state.fileTypes,
lastModified: this.state.lastModified,
@@ -289,7 +292,7 @@ class Search extends React.Component<Props, State> {
this.props.searchLocationIndex(searchQuery);
};
- handleSearchMenu = (event: React.ChangeEvent<HTMLInputElement>) => {
+ handleSearchMenu = (event: any) => {
this.setState({
searchMenuOpened: true,
searchMenuAnchorEl: event.currentTarget
@@ -322,12 +325,6 @@ class Search extends React.Component<Props, State> {
? 'disabled while indexing...'
: 'in ' + indexedEntriesCount + ' indexed entries'}
</Typography>
- {/* <IconButton
- data-tid="helpSearchButton"
- onClick={() => {}}
- >
- <HelpIcon />
- </IconButton> */}
<IconButton
style={{ marginLeft: 'auto' }}
data-tid="searchMenu"
diff --git a/app/components/TagsSelect.tsx b/app/components/TagsSelect.tsx
index 5487c06b3..a748ccefd 100644
--- a/app/components/TagsSelect.tsx
+++ b/app/components/TagsSelect.tsx
@@ -198,16 +198,16 @@ const components = {
};
interface Props {
- classes: any;
- theme: any;
+ classes?: any;
+ theme?: any;
tags: Array<Tag>;
- tagSearchType: string;
+ tagSearchType?: string;
defaultBackgroundColor?: string;
defaultTextColor?: string;
- handleChange: (param1: any, param2: any, param3: any) => void;
- allTags: Array<Tag>;
+ handleChange?: (param1: any, param2: any, param3: any) => void;
+ allTags?: Array<Tag>;
isReadOnlyMode?: boolean;
- placeholderText: string;
+ placeholderText?: string;
}
const TagsSelect = (props: Props) => {
diff --git a/app/components/VerticalNavigation.tsx b/app/components/VerticalNavigation.tsx
index 07a6c4a2b..1f63642f5 100644
--- a/app/components/VerticalNavigation.tsx
+++ b/app/components/VerticalNavigation.tsx
@@ -1,4 +1,3 @@
-// @ts-nocheck
/**
* TagSpaces - universal file and folder organizer
* Copyright (C) 2017-present TagSpaces UG (haftungsbeschraenkt)
@@ -88,7 +87,7 @@ interface Props {
closeAllVerticalPanels: () => void;
openFileNatively: (url: string) => void;
openURLExternally: (url: string) => void;
- switchTheme: () => void;
+ switchTheme: (theme: string) => void;
showNotification: (message: string) => void;
isReadOnlyMode: boolean;
}
@@ -327,6 +326,7 @@ class VerticalNavigation extends React.Component<Props, State> {
title={i18n.t('core:upgradeToPro')}
data-tid="upgradeToPro"
onClick={this.toggleProTeaser}
+ // @ts-ignore
style={{ ...this.styles.button, ...this.styles.upgradeButton }}
>
<UpgradeIcon
@@ -342,6 +342,7 @@ class VerticalNavigation extends React.Component<Props, State> {
title={i18n.t('core:switchTheme')}
data-tid="switchTheme"
onClick={switchTheme}
+ // @ts-ignore
style={{ ...this.styles.button, ...this.styles.themingButton }}
>
<ThemingIcon style={this.styles.buttonIcon} />
@@ -351,6 +352,7 @@ class VerticalNavigation extends React.Component<Props, State> {
title={i18n.t('core:settings')}
data-tid="settings"
onClick={toggleSettingsDialog}
+ // @ts-ignore
style={
isSettingsDialogOpened
? {
@@ -377,7 +379,6 @@ class VerticalNavigation extends React.Component<Props, State> {
<Search
style={{ display: isSearchPanelOpened ? 'block' : 'none' }}
/>
- {isPerspectivesPanelOpened && <PerspectiveManager />}
{isHelpFeedbackPanelOpened && (
<HelpFeedbackPanel
openFileNatively={openFileNatively}
diff --git a/app/components/dialogs/AddRemoveTagsDialog.tsx b/app/components/dialogs/AddRemoveTagsDialog.tsx
index 91b125db5..adb7da476 100644
--- a/app/components/dialogs/AddRemoveTagsDialog.tsx
+++ b/app/components/dialogs/AddRemoveTagsDialog.tsx
@@ -1,4 +1,3 @@
-// @ts-nocheck
/**
* TagSpaces - universal file and folder organizer
* Copyright (C) 2017-present TagSpaces UG (haftungsbeschraenkt)
@@ -107,7 +106,7 @@ class AddRemoveTagsDialog extends React.Component<Props, State> {
keepMounted
scroll="paper"
// onEnterKey={(event) => onEnterKeyHandler(event, this.addTags)}
- TransitionComponent={Transition}
+ // TransitionComponent={Transition}
>
<DialogTitle>{i18n.t('core:tagOperationTitle')}</DialogTitle>
<DialogContent style={{ minHeight: 330 }}>
diff --git a/app/components/dialogs/CreateFileDialog.tsx b/app/components/dialogs/CreateFileDialog.tsx
index 8ed526e54..7488cbda0 100644
--- a/app/components/dialogs/CreateFileDialog.tsx
+++ b/app/components/dialogs/CreateFileDialog.tsx
@@ -1,4 +1,3 @@
-// @ts-nocheck
/**
* TagSpaces - universal file and folder organizer
* Copyright (C) 2017-present TagSpaces UG (haftungsbeschraenkt)
@@ -117,6 +116,7 @@ class CreateFileDialog extends React.Component<Props, State> {
const value = target.type === 'checkbox' ? target.checked : target.value;
const name = target.name;
this.setState(
+ // @ts-ignore
{
[name]: value
},
@@ -192,9 +192,9 @@ class CreateFileDialog extends React.Component<Props, State> {
return = () => {
<Dialog
- open={open}
- onClose={onClose}
- fullScreen={fullScreen}
+ open={this.props.open}
+ onClose={this.props.onClose}
+ fullScreen={this.props.fullScreen}
keepMounted
scroll="paper"
// onKeyDown={confirmFunction}
@@ -267,6 +267,7 @@ class CreateFileDialog extends React.Component<Props, State> {
required
margin="dense"
name="selectedDirectoryPath"
+ // @ts-ignore
label={i18n.t('core:filePath')}
fullWidth={true}
data-tid="createFileDialog_filePath"
diff --git a/app/components/menus/LocationMenu.tsx b/app/components/menus/LocationMenu.tsx
index c0d908409..781f2a634 100644
--- a/app/components/menus/LocationMenu.tsx
+++ b/app/components/menus/LocationMenu.tsx
@@ -1,4 +1,3 @@
-// @ts-nocheck
/**
* TagSpaces - universal file and folder organizer
* Copyright (C) 2017-present TagSpaces UG (haftungsbeschraenkt)
@@ -78,9 +77,7 @@ class LocationMenu extends React.Component<Props, State> {
this.toggleLocationChooser(undefined);
};
- toggleLocationChooser = (
- event: React.ChangeEvent<HTMLInputElement> | undefined
- ) => {
+ toggleLocationChooser = (event: any) => {
this.setState({
locationChooserMenuOpened: !this.state.locationChooserMenuOpened,
locationChooserMenuAnchorEl: event ? event.currentTarget : null
diff --git a/app/containers/MainPage.tsx b/app/containers/MainPage.tsx
index d73746c40..d61ade3a3 100644
--- a/app/containers/MainPage.tsx
+++ b/app/containers/MainPage.tsx
@@ -1,4 +1,3 @@
-// @ts-nocheck
/**
* TagSpaces - universal file and folder organizer
* Copyright (C) 2017-present TagSpaces UG (haftungsbeschraenkt)
@@ -772,7 +771,11 @@ class MainPage extends Component<Props, State> {
]}
/>
{this.props.isDesktopMode ? (
- <TargetFileBox accepts={[FILE]} onDrop={this.handleFileDrop}>
+ <TargetFileBox
+ // @ts-ignore
+ accepts={[FILE]}
+ onDrop={this.handleFileDrop}
+ >
<SplitPane
split="vertical"
minSize={200}
@@ -802,6 +805,7 @@ class MainPage extends Component<Props, State> {
onChange={size => {
if (size > 0 && this.state.width) {
const sizeInPercent =
+ // @ts-ignore
parseInt((size * 100) / this.state.width, 10) + '%';
this.setState({
mainSplitSize: sizeInPercent
@@ -839,6 +843,7 @@ class MainPage extends Component<Props, State> {
onChange={size => {
if (size > 0 && this.state.width) {
const sizeInPercent =
+ // @ts-ignore
parseInt((size * 100) / this.state.width, 10) + '%';
this.setState({
mainSplitSize: sizeInPercent
diff --git a/app/perspectives/grid-perspective/components/CellContent.tsx b/app/perspectives/grid-perspective/components/CellContent.tsx
index 1b895d16a..84c1c9245 100644
--- a/app/perspectives/grid-perspective/components/CellContent.tsx
+++ b/app/perspectives/grid-perspective/components/CellContent.tsx
@@ -1,4 +1,3 @@
-// @ts-nocheck
/**
* TagSpaces - universal file and folder organizer
* Copyright (C) 2017-present TagSpaces UG (haftungsbeschraenkt)
@@ -206,6 +205,7 @@ const CellContent = (props: Props) => {
<FolderIcon
className={classes.gridFolder}
style={{ backgroundColor: fsEntryColor }}
+ // @ts-ignore
title={fsEntry.path}
/>
</div>
@@ -349,7 +349,7 @@ const CellContent = (props: Props) => {
entryHeight = 130;
}
- let gridCell = React.Fragment;
+ let gridCell: any = React.Fragment;
if (layoutType === 'grid') {
gridCell = renderGridCell();
} else if (layoutType === 'row') {
diff --git a/app/utils/misc.ts b/app/utils/misc.ts
index 842ef7aae..e1fd97064 100644
--- a/app/utils/misc.ts
+++ b/app/utils/misc.ts
@@ -1,4 +1,3 @@
-// @ts-nocheck
/**
* TagSpaces - universal file and folder organizer
* Copyright (C) 2017-present TagSpaces UG (haftungsbeschraenkt)
@@ -19,75 +18,75 @@
/** Returns true is a string is plus code e.g. 8FWH4HVG+3V 8FWH4HVG+ 8FWH4H+ */
export function isPlusCode(plusCode: string): boolean {
- if (!plusCode) {
- return false;
- }
- const upperCasedPlusCode = plusCode.toUpperCase(); // needed only lowercased index
- return /(^|\s)([23456789C][23456789CFGHJMPQRV][23456789CFGHJMPQRVWX]{6}\+[23456789CFGHJMPQRVWX]{2,3})(\s|$)/.test(
- upperCasedPlusCode
- );
+ if (!plusCode) {
+ return false;
+ }
+ const upperCasedPlusCode = plusCode.toUpperCase(); // needed only lowercased index
+ return /(^|\s)([23456789C][23456789CFGHJMPQRV][23456789CFGHJMPQRVWX]{6}\+[23456789CFGHJMPQRVWX]{2,3})(\s|$)/.test(
+ upperCasedPlusCode
+ );
}
export function parseLatLon(
- latLongInput: string
+ latLongInput: string
): { lat: number; lon: number } | false {
- const cleanedInput = latLongInput.replace(/\s+/g, ''); // cleaning spaces
- if (
- !/^[-+]?([1-8]?\d(\.\d+)?|90(\.0+)?),\s*[-+]?(180(\.0+)?|((1[0-7]\d)|([1-9]?\d))(\.\d+)?)$/.test(
- cleanedInput
- )
- ) {
- return false;
- }
- const latLongArray = cleanedInput.split(',');
- const lat = parseFloat(latLongArray[0]);
- const lon = parseFloat(latLongArray[1]);
- if (!isNaN(lat) && !isNaN(lon)) {
- return {
- lat,
- lon
- };
- }
- return false;
+ const cleanedInput = latLongInput.replace(/\s+/g, ''); // cleaning spaces
+ if (
+ !/^[-+]?([1-8]?\d(\.\d+)?|90(\.0+)?),\s*[-+]?(180(\.0+)?|((1[0-7]\d)|([1-9]?\d))(\.\d+)?)$/.test(
+ cleanedInput
+ )
+ ) {
+ return false;
+ }
+ const latLongArray = cleanedInput.split(',');
+ const lat = parseFloat(latLongArray[0]);
+ const lon = parseFloat(latLongArray[1]);
+ if (!isNaN(lat) && !isNaN(lon)) {
+ return {
+ lat,
+ lon
+ };
+ }
+ return false;
}
export function traverse(objArr: Array<Object>, func: any) {
- objArr.forEach(obj => {
- Object.keys(obj).map(objKey => {
- func.apply(this, [obj, objKey]);
- if (objKey === 'subPages' && typeof Array.isArray(obj[objKey])) {
- traverse(obj[objKey], func);
- }
- return true;
- });
- });
+ objArr.forEach(obj => {
+ Object.keys(obj).map(objKey => {
+ func.apply(this, [obj, objKey]);
+ if (objKey === 'subPages' && typeof Array.isArray(obj[objKey])) {
+ traverse(obj[objKey], func);
+ }
+ return true;
+ });
+ });
}
export function immutablySwapItems(
- items: any,
- firstIndex: number,
- secondIndex: number
+ items: any,
+ firstIndex: number,
+ secondIndex: number
) {
- const results = items.slice();
- const firstItem = items[firstIndex];
- results[firstIndex] = items[secondIndex];
- results[secondIndex] = firstItem;
- return results;
+ const results = items.slice();
+ const firstItem = items[firstIndex];
+ results[firstIndex] = items[secondIndex];
+ results[secondIndex] = firstItem;
+ return results;
}
export function hasURLProtocol(url: string) {
- return (
- url.startsWith('http://') ||
- url.startsWith('https://') ||
- url.startsWith('file://') ||
- url.startsWith('data:')
- );
+ return (
+ url.startsWith('http://') ||
+ url.startsWith('https://') ||
+ url.startsWith('file://') ||
+ url.startsWith('data:')
+ );
}
export function arrayBufferToDataURL(arrayBuffer: any, mime: string) {
- const blob = new Blob([arrayBuffer], { type: mime });
- const url = window.URL || window.webkitURL;
- return url.createObjectURL(blob);
+ const blob = new Blob([arrayBuffer], { type: mime });
+ const url = window.URL || window.webkitURL;
+ return url.createObjectURL(blob);
}
/**
@@ -100,359 +99,361 @@ export function arrayBufferToDataURL(arrayBuffer: any, mime: string) {
* @returns {Blob}
*/
export function b64toBlob(
- b64Data: any,
- contentType: string = '',
- sliceSize: number = 512
+ b64Data: any,
+ contentType: string = '',
+ sliceSize: number = 512
) {
- const byteCharacters = atob(b64Data);
- const byteArrays = [];
-
- for (let offset = 0; offset < byteCharacters.length; offset += sliceSize) {
- const slice = byteCharacters.slice(offset, offset + sliceSize);
- const byteNumbers = new Array(slice.length);
- for (let i = 0; i < slice.length; i += 1) {
- byteNumbers[i] = slice.charCodeAt(i);
- }
- const byteArray = new Uint8Array(byteNumbers);
- byteArrays.push(byteArray);
- }
- const blob = new Blob(byteArrays, { type: contentType });
- return blob;
+ const byteCharacters = atob(b64Data);
+ const byteArrays = [];
+
+ for (let offset = 0; offset < byteCharacters.length; offset += sliceSize) {
+ const slice = byteCharacters.slice(offset, offset + sliceSize);
+ const byteNumbers = new Array(slice.length);
+ for (let i = 0; i < slice.length; i += 1) {
+ byteNumbers[i] = slice.charCodeAt(i);
+ }
+ const byteArray = new Uint8Array(byteNumbers);
+ byteArrays.push(byteArray);
+ }
+ const blob = new Blob(byteArrays, { type: contentType });
+ return blob;
}
export function getRandomInt(min: number, max: number) {
- return Math.floor(Math.random() * (max - min + 1)) + min;
+ return Math.floor(Math.random() * (max - min + 1)) + min;
}
export function isVisibleOnScreen(element: any) {
- const rectangle = element.getBoundingClientRect();
- const isVisible =
- rectangle.top >= 0 &&
- rectangle.left >= 0 &&
- rectangle.bottom <=
- (window.innerHeight || document.documentElement.clientHeight) &&
- rectangle.right <=
- (window.innerWidth || document.documentElement.clientWidth);
- return isVisible;
+ const rectangle = element.getBoundingClientRect();
+ const isVisible =
+ rectangle.top >= 0 &&
+ rectangle.left >= 0 &&
+ rectangle.bottom <=
+ (window.innerHeight || document.documentElement.clientHeight) &&
+ rectangle.right <=
+ (window.innerWidth || document.documentElement.clientWidth);
+ return isVisible;
}
export function getURLParameter(variable: string) {
- const query = window.location.search.substring(1);
- const vars = query.split('&');
- for (let i = 0; i < vars.length; i += 1) {
- const pair = vars[i].split('=');
- if (pair[0] === variable) {
- return pair[1];
- }
- }
- return false;
+ const query = window.location.search.substring(1);
+ const vars = query.split('&');
+ for (let i = 0; i < vars.length; i += 1) {
+ const pair = vars[i].split('=');
+ if (pair[0] === variable) {
+ return pair[1];
+ }
+ }
+ return false;
}
export function dataURLtoBlob(dataURI) {
- const arr = dataURI.split(',');
- const mime = arr[0].match(/:(.*?);/)[1];
- const arrBuff = base64ToArrayBuffer(arr[1]);
- return new window.Blob([arrBuff], { type: mime });
+ const arr = dataURI.split(',');
+ const mime = arr[0].match(/:(.*?);/)[1];
+ const arrBuff = base64ToArrayBuffer(arr[1]);
+ return new window.Blob([arrBuff], { type: mime });
}
export function base64ToArrayBuffer(base64) {
- const bstr = window.atob(base64);
- const bytes = new Uint8Array(bstr.length);
- for (let i = 0; i < bstr.length; i += 1) {
- bytes[i] = bstr.charCodeAt(i);
- }
- return bytes.buffer;
+ const bstr = window.atob(base64);
+ const bytes = new Uint8Array(bstr.length);
+ for (let i = 0; i < bstr.length; i += 1) {
+ bytes[i] = bstr.charCodeAt(i);
+ }
+ return bytes.buffer;
}
export function arrayBufferToBuffer(content: any) {
- const buffer = new Buffer(content.byteLength);
- const view = new Uint8Array(content);
- for (let i = 0; i < buffer.length; ++i) {
- buffer[i] = view[i];
- }
- return buffer;
+ const buffer = new Buffer(content.byteLength);
+ const view = new Uint8Array(content);
+ for (let i = 0; i < buffer.length; ++i) {
+ buffer[i] = view[i];
+ }
+ return buffer;
}
export function getBase64Image(imgURL: string) {
- const canvas = document.createElement('canvas');
- const img = new Image();
- img.crossOrigin = 'anonymous';
- img.src = imgURL;
- canvas.width = img.width;
- canvas.height = img.height;
- const ctx = canvas.getContext('2d');
- ctx.drawImage(img, 0, 0);
- return canvas.toDataURL('image/png');
+ const canvas = document.createElement('canvas');
+ const img = new Image();
+ img.crossOrigin = 'anonymous';
+ img.src = imgURL;
+ canvas.width = img.width;
+ canvas.height = img.height;
+ const ctx = canvas.getContext('2d');
+ ctx.drawImage(img, 0, 0);
+ return canvas.toDataURL('image/png');
}
export function formatFileSize(sizeInBytes: number): string {
- const kilobyte = 1024;
- const megabyte = kilobyte * kilobyte;
- const gigabyte = megabyte * kilobyte;
- const terabyte = gigabyte * kilobyte;
- const precision = 2;
-
- if (sizeInBytes >= 0 && sizeInBytes < kilobyte) {
- return sizeInBytes + ' B';
- } else if (sizeInBytes >= kilobyte && sizeInBytes < megabyte) {
- return (sizeInBytes / kilobyte).toFixed(precision) + ' KB';
- } else if (sizeInBytes >= megabyte && sizeInBytes < gigabyte) {
- return (sizeInBytes / megabyte).toFixed(precision) + ' MB';
- } else if (sizeInBytes >= gigabyte && sizeInBytes < terabyte) {
- return (sizeInBytes / gigabyte).toFixed(precision) + ' GB';
- } else if (sizeInBytes >= terabyte) {
- return (sizeInBytes / terabyte).toFixed(precision) + ' TB';
- }
- return sizeInBytes + '';
+ const kilobyte = 1024;
+ const megabyte = kilobyte * kilobyte;
+ const gigabyte = megabyte * kilobyte;
+ const terabyte = gigabyte * kilobyte;
+ const precision = 2;
+
+ if (sizeInBytes >= 0 && sizeInBytes < kilobyte) {
+ return sizeInBytes + ' B';
+ } else if (sizeInBytes >= kilobyte && sizeInBytes < megabyte) {
+ return (sizeInBytes / kilobyte).toFixed(precision) + ' KB';
+ } else if (sizeInBytes >= megabyte && sizeInBytes < gigabyte) {
+ return (sizeInBytes / megabyte).toFixed(precision) + ' MB';
+ } else if (sizeInBytes >= gigabyte && sizeInBytes < terabyte) {
+ return (sizeInBytes / gigabyte).toFixed(precision) + ' GB';
+ } else if (sizeInBytes >= terabyte) {
+ return (sizeInBytes / terabyte).toFixed(precision) + ' TB';
+ }
+ return sizeInBytes + '';
}
export function formatFileSize2(
- sizeInBytes: number,
- siSystem: boolean
+ sizeInBytes: number,
+ siSystem: boolean
): string {
- const threshold = siSystem ? 1000 : 1024;
- if (!sizeInBytes) {
- return '';
- }
- if (sizeInBytes < threshold) {
- return sizeInBytes + ' B';
- }
- const units = siSystem
- ? ['kB', 'MB', 'GB', 'TB', 'PB', 'EB']
- : ['KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB'];
- let cUnit = -1;
- do {
- sizeInBytes /= threshold;
- ++cUnit;
- } while (sizeInBytes >= threshold);
- return sizeInBytes.toFixed(1) + ' ' + units[cUnit];
+ const threshold = siSystem ? 1000 : 1024;
+ if (!sizeInBytes) {
+ return '';
+ }
+ if (sizeInBytes < threshold) {
+ return sizeInBytes + ' B';
+ }
+ const units = siSystem
+ ? ['kB', 'MB', 'GB', 'TB', 'PB', 'EB']
+ : ['KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB'];
+ let cUnit = -1;
+ do {
+ sizeInBytes /= threshold;
+ ++cUnit;
+ } while (sizeInBytes >= threshold);
+ return sizeInBytes.toFixed(1) + ' ' + units[cUnit];
}
-export function formatDateTime(date: string, includeTime: boolean) {
- if (date === undefined || date === '') {
- return '';
- }
- const d = new Date(date);
- let cDate: string = '' + d.getDate();
- cDate += '';
- if (cDate.length === 1) {
- cDate = '0' + cDate;
- }
- let cMonth: string = '' + (d.getMonth() + 1);
- cMonth += '';
- if (cMonth.length === 1) {
- cMonth = '0' + cMonth;
- }
- const cYear: string = '' + d.getFullYear();
- let cHour: string = '' + d.getHours();
- cHour += '';
- if (cHour.length === 1) {
- cHour = '0' + cHour;
- }
- let cMinute: string = '' + d.getMinutes();
- cMinute += '';
- if (cMinute.length === 1) {
- cMinute = '0' + cMinute;
- }
- let cSecond: string = '' + d.getSeconds();
- cSecond += '';
- if (cSecond.length === 1) {
- cSecond = '0' + cSecond;
- }
- let time = '';
- if (includeTime) {
- time = ' - ' + cHour + ':' + cMinute + ':' + cSecond;
- }
- return cYear + '.' + cMonth + '.' + cDate + time;
+export function formatDateTime(date: string | number, includeTime: boolean) {
+ if (date === undefined || date === '') {
+ return '';
+ }
+ const d = new Date(date);
+ let cDate: string = '' + d.getDate();
+ cDate += '';
+ if (cDate.length === 1) {
+ cDate = '0' + cDate;
+ }
+ let cMonth: string = '' + (d.getMonth() + 1);
+ cMonth += '';
+ if (cMonth.length === 1) {
+ cMonth = '0' + cMonth;
+ }
+ const cYear: string = '' + d.getFullYear();
+ let cHour: string = '' + d.getHours();
+ cHour += '';
+ if (cHour.length === 1) {
+ cHour = '0' + cHour;
+ }
+ let cMinute: string = '' + d.getMinutes();
+ cMinute += '';
+ if (cMinute.length === 1) {
+ cMinute = '0' + cMinute;
+ }
+ let cSecond: string = '' + d.getSeconds();
+ cSecond += '';
+ if (cSecond.length === 1) {
+ cSecond = '0' + cSecond;
+ }
+ let time = '';
+ if (includeTime) {
+ time = ' - ' + cHour + ':' + cMinute + ':' + cSecond;
+ }
+ return cYear + '.' + cMonth + '.' + cDate + time;
}
/** Convert a date in the following format 20191204 or 20191204~124532 */
export function formatDateTime4Tag(
- date: string | Date,
- includeTime: boolean,
- includeMS?: boolean
+ date: string | Date,
+ includeTime: boolean,
+ includeMS?: boolean
): string {
- if (date === undefined || date === '') {
- return '';
- }
- const d = new Date(date);
- let cDate: string = '' + d.getDate();
- cDate += '';
- if (cDate.length === 1) {
- cDate = '0' + cDate;
- }
- let cMonth: string = '' + (d.getMonth() + 1);
- cMonth += '';
- if (cMonth.length === 1) {
- cMonth = '0' + cMonth;
- }
- const cYear = d.getFullYear();
-
- let time = '';
- if (includeTime) {
- let cHour: string = '' + d.getHours();
- cHour += '';
- if (cHour.length === 1) {
- cHour = '0' + cHour;
- }
- let cMinute: string = '' + d.getMinutes();
- cMinute += '';
- if (cMinute.length === 1) {
- cMinute = '0' + cMinute;
- }
- let cSecond: string = '' + d.getSeconds();
- cSecond += '';
- if (cSecond.length === 1) {
- cSecond = '0' + cSecond;
- }
- time = '~' + cHour + '' + cMinute + '' + cSecond; // TODO fix Chrome transforms ~ to _
- }
-
- let milliseconds = '';
- if (includeMS) {
- milliseconds = '~' + d.getMilliseconds();
- }
- return cYear + '' + cMonth + '' + cDate + time + milliseconds;
+ if (date === undefined || date === '') {
+ return '';
+ }
+ const d = new Date(date);
+ let cDate: string = '' + d.getDate();
+ cDate += '';
+ if (cDate.length === 1) {
+ cDate = '0' + cDate;
+ }
+ let cMonth: string = '' + (d.getMonth() + 1);
+ cMonth += '';
+ if (cMonth.length === 1) {
+ cMonth = '0' + cMonth;
+ }
+ const cYear = d.getFullYear();
+
+ let time = '';
+ if (includeTime) {
+ let cHour: string = '' + d.getHours();
+ cHour += '';
+ if (cHour.length === 1) {
+ cHour = '0' + cHour;
+ }
+ let cMinute: string = '' + d.getMinutes();
+ cMinute += '';
+ if (cMinute.length === 1) {
+ cMinute = '0' + cMinute;
+ }
+ let cSecond: string = '' + d.getSeconds();
+ cSecond += '';
+ if (cSecond.length === 1) {
+ cSecond = '0' + cSecond;
+ }
+ time = '~' + cHour + '' + cMinute + '' + cSecond; // TODO fix Chrome transforms ~ to _
+ }
+
+ let milliseconds = '';
+ if (includeMS) {
+ milliseconds = '~' + d.getMilliseconds();
+ }
+ return cYear + '' + cMonth + '' + cDate + time + milliseconds;
}
export function convertStringToDate(dateString: string) {
- if (dateString === undefined || dateString === '') {
- return false;
- }
- if (dateString.length === 8) {
- return new Date(
- dateString.substring(0, 4) +
- '-' +
- dateString.substring(4, 6) +
- '-' +
- dateString.substring(6, 8)
- );
- }
- return false;
+ if (dateString === undefined || dateString === '') {
+ return false;
+ }
+ if (dateString.length === 8) {
+ return new Date(
+ dateString.substring(0, 4) +
+ '-' +
+ dateString.substring(4, 6) +
+ '-' +
+ dateString.substring(6, 8)
+ );
+ }
+ return false;
}
export function sortAlphaNum(a: any, b: any) {
- // Regular expression to separate the digit string from the non-digit strings.
- const reParts = /\d+|\D+/g;
-
- // Regular expression to test if the string has a digit.
- const reDigit = /\d/;
-
- // Get rid of casing issues.
- a = a.name.toLowerCase();
- b = b.name.toLowerCase();
-
- // Separates the strings into substrings that have only digits and those
- // that have no digits.
- const aParts = a.match(reParts);
- const bParts = b.match(reParts);
-
- // Used to determine if aPart and bPart are digits.
- let isDigitPart;
-
- // If `a` and `b` are strings with substring parts that match...
- if (
- aParts &&
- bParts &&
- (isDigitPart = reDigit.test(aParts[0])) === reDigit.test(bParts[0])
- ) {
- // Loop through each substring part to compare the overall strings.
- const len = Math.min(aParts.length, bParts.length);
- for (let i = 0; i < len; i += 1) {
- let aPart = aParts[i];
- let bPart = bParts[i];
-
- // If comparing digits, convert them to numbers (assuming base 10).
- if (isDigitPart) {
- aPart = parseInt(aPart, 10);
- bPart = parseInt(bPart, 10);
- }
-
- // If the substrings aren't equal, return either -1 or 1.
- if (aPart !== bPart) {
- return aPart < bPart ? -1 : 1;
- }
-
- // Toggle the value of isDigitPart since the parts will alternate.
- isDigitPart = !isDigitPart;
- }
- }
-
- // Use normal comparison.
- return (a >= b) - (a <= b);
+ // Regular expression to separate the digit string from the non-digit strings.
+ const reParts = /\d+|\D+/g;
+
+ // Regular expression to test if the string has a digit.
+ const reDigit = /\d/;
+
+ // Get rid of casing issues.
+ a = a.name.toLowerCase();
+ b = b.name.toLowerCase();
+
+ // Separates the strings into substrings that have only digits and those
+ // that have no digits.
+ const aParts = a.match(reParts);
+ const bParts = b.match(reParts);
+
+ // Used to determine if aPart and bPart are digits.
+ let isDigitPart;
+
+ // If `a` and `b` are strings with substring parts that match...
+ if (
+ aParts &&
+ bParts &&
+ (isDigitPart = reDigit.test(aParts[0])) === reDigit.test(bParts[0])
+ ) {
+ // Loop through each substring part to compare the overall strings.
+ const len = Math.min(aParts.length, bParts.length);
+ for (let i = 0; i < len; i += 1) {
+ let aPart = aParts[i];
+ let bPart = bParts[i];
+
+ // If comparing digits, convert them to numbers (assuming base 10).
+ if (isDigitPart) {
+ aPart = parseInt(aPart, 10);
+ bPart = parseInt(bPart, 10);
+ }
+
+ // If the substrings aren't equal, return either -1 or 1.
+ if (aPart !== bPart) {
+ return aPart < bPart ? -1 : 1;
+ }
+
+ // Toggle the value of isDigitPart since the parts will alternate.
+ isDigitPart = !isDigitPart;
+ }
+ }
+
+ // Use normal comparison.
+ // @ts-ignore
+ return (a >= b) - (a <= b);
}
// Sorting functionality
export function sortByName(a: any, b: any) {
- return !b.isFile - !a.isFile || sortAlphaNum(a, b);
+ // @ts-ignore
+ return !b.isFile - !a.isFile || sortAlphaNum(a, b);
}
export function sortBySize(a: any, b: any) {
- return a.size - b.size;
+ return a.size - b.size;
}
export function sortByDateModified(a: any, b: any) {
- return a.lmdt - b.lmdt;
+ return a.lmdt - b.lmdt;
}
export function sortByExtension(a: any, b: any) {
- return a.extension.toString().localeCompare(b.extension);
+ return a.extension.toString().localeCompare(b.extension);
}
export function sortByFirstTag(a: any, b: any) {
- if ((!a.tags && !b.tags) || (a.tags.length < 1 && b.tags.length < 1)) {
- return 0;
- }
- if (!a.tags || a.tags.length < 1) {
- return -1;
- }
- if (!b.tags || b.tags.length < 1) {
- return 1;
- }
- return a.tags[0].title.localeCompare(b.tags[0].title);
+ if ((!a.tags && !b.tags) || (a.tags.length < 1 && b.tags.length < 1)) {
+ return 0;
+ }
+ if (!a.tags || a.tags.length < 1) {
+ return -1;
+ }
+ if (!b.tags || b.tags.length < 1) {
+ return 1;
+ }
+ return a.tags[0].title.localeCompare(b.tags[0].title);
}
export function shuffleArray(array: Array<any>) {
- // Durstenfeld shuffle
- for (let i = array.length - 1; i > 0; i--) {
- const j = Math.floor(Math.random() * (i + 1));
- [array[i], array[j]] = [array[j], array[i]];
- }
- return array;
+ // Durstenfeld shuffle
+ for (let i = array.length - 1; i > 0; i--) {
+ const j = Math.floor(Math.random() * (i + 1));
+ [array[i], array[j]] = [array[j], array[i]];
+ }
+ return array;
}
export function sortByCriteria(data: any, criteria: string, order: boolean) {
- switch (criteria) {
- case 'byName':
- if (order) {
- return data.sort(sortByName);
- }
- return data.sort((a, b) => -1 * sortByName(a, b));
- case 'byFileSize':
- if (order) {
- return data.sort(sortBySize);
- }
- return data.sort((a, b) => -1 * sortBySize(a, b));
- case 'byDateModified':
- if (order) {
- return data.sort(sortByDateModified);
- }
- return data.sort((a, b) => -1 * sortByDateModified(a, b));
- case 'byExtension':
- if (order) {
- return data.sort(sortByExtension);
- }
- return data.sort((a, b) => -1 * sortByExtension(a, b));
- case 'byFirstTag':
- if (order) {
- return data.sort(sortByFirstTag);
- }
- return data.sort((a, b) => -1 * sortByFirstTag(a, b));
- case 'random':
- return shuffleArray(data);
- default:
- return data.sort(sortByName);
- }
+ switch (criteria) {
+ case 'byName':
+ if (order) {
+ return data.sort(sortByName);
+ }
+ return data.sort((a, b) => -1 * sortByName(a, b));
+ case 'byFileSize':
+ if (order) {
+ return data.sort(sortBySize);
+ }
+ return data.sort((a, b) => -1 * sortBySize(a, b));
+ case 'byDateModified':
+ if (order) {
+ return data.sort(sortByDateModified);
+ }
+ return data.sort((a, b) => -1 * sortByDateModified(a, b));
+ case 'byExtension':
+ if (order) {
+ return data.sort(sortByExtension);
+ }
+ return data.sort((a, b) => -1 * sortByExtension(a, b));
+ case 'byFirstTag':
+ if (order) {
+ return data.sort(sortByFirstTag);
+ }
+ return data.sort((a, b) => -1 * sortByFirstTag(a, b));
+ case 'random':
+ return shuffleArray(data);
+ default:
+ return data.sort(sortByName);
+ }
}
/**
@@ -461,7 +462,7 @@ export function sortByCriteria(data: any, criteria: string, order: boolean) {
* @returns {boolean}
*/
export const isObj = (val: any) =>
- typeof val === 'object' && !isArr(val) && !isNull(val);
+ typeof val === 'object' && !isArr(val) && !isNull(val);
/**
* @description Check if value is of type 'null'
@@ -512,19 +513,19 @@ export const isBool = (val: any) => typeof val === 'boolean';
* Check if object has property
*/
export const hasProp = (obj: Object, prop: any): boolean =>
- obj.hasOwnProperty(prop);
+ obj.hasOwnProperty(prop);
/**
* Check if object has method
*/
export const hasMethod = (obj: Object, method: any): boolean =>
- hasProp(obj, method) && isFunc(obj[method]);
+ hasProp(obj, method) && isFunc(obj[method]);
/**
* Check if object has key
*/
export const hasKey = (obj: Object, key: any): boolean =>
- getKeys(obj).indexOf(key) > -1;
+ getKeys(obj).indexOf(key) > -1;
/**
* @description Get object keys
@@ -539,7 +540,7 @@ export const getKeys = (obj: Object) => Object.keys(obj);
* @param callback
*/
export const eachKey = (obj, callback) => {
- Object.keys(obj).forEach((key, index) => callback(key, obj[key], index));
+ Object.keys(obj).forEach((key, index) => callback(key, obj[key], index));
};
/**
@@ -548,7 +549,7 @@ export const eachKey = (obj, callback) => {
* @param callback
*/
export const eachProp = (obj, callback) => {
- eachKey(obj, (key, prop, index) => callback(prop, key, index));
+ eachKey(obj, (key, prop, index) => callback(prop, key, index));
};
/**
@@ -558,11 +559,11 @@ export const eachProp = (obj, callback) => {
* @returns {object}
*/
export const extend = (baseObject, ...restObjects) => {
- const assign = Object.assign;
- const modifiedObject = assign({}, baseObject);
+ const assign = Object.assign;
+ const modifiedObject = assign({}, baseObject);
- restObjects.map(obj => assign(modifiedObject, obj));
- return modifiedObject;
+ restObjects.map(obj => assign(modifiedObject, obj));
+ return modifiedObject;
};
/**
@@ -573,13 +574,13 @@ export const extend = (baseObject, ...restObjects) => {
* @returns {*}
*/
export const recurIter = (handler, complete, index = 0) => {
- handler(canRecur => {
- if (!canRecur) {
- return complete();
- }
- const nextIndex = index + 1;
- recurIter(handler, complete, nextIndex);
- }, index);
+ handler(canRecur => {
+ if (!canRecur) {
+ return complete();
+ }
+ const nextIndex = index + 1;
+ recurIter(handler, complete, nextIndex);
+ }, index);
};
/**
@@ -589,14 +590,14 @@ export const recurIter = (handler, complete, index = 0) => {
* @param interval
*/
export const poll = (handler, complete, interval) => {
- setTimeout(() => {
- handler(canPoll => {
- if (canPoll) {
- return poll(handler, complete, interval);
- }
- complete();
- });
- }, interval);
+ setTimeout(() => {
+ handler(canPoll => {
+ if (canPoll) {
+ return poll(handler, complete, interval);
+ }
+ complete();
+ });
+ }, interval);
};
/**
@@ -604,17 +605,17 @@ export const poll = (handler, complete, interval) => {
* @returns {function(*=, *=, *=)}
*/
export const buffer = ({ timeout, id }) => {
- const timers = {};
-
- return callback => {
- if (!id) {
- timers[id] = '0';
- }
- if (timers[id]) {
- clearTimeout(timers[id]);
- }
- timers[id] = setTimeout(callback, timeout);
- };
+ const timers = {};
+
+ return callback => {
+ if (!id) {
+ timers[id] = '0';
+ }
+ if (timers[id]) {
+ clearTimeout(timers[id]);
+ }
+ timers[id] = setTimeout(callback, timeout);
+ };
};
/**
@@ -623,55 +624,26 @@ export const buffer = ({ timeout, id }) => {
* @returns {*}
*/
export const determineTypeChecker = type => {
- switch (type) {
- case 'number':
- return isNum;
- case 'object':
- return isObj;
- case 'null':
- return isNull;
- case 'function':
- return isFunc;
- case 'array':
- return isArr;
- case 'string':
- return isStr;
- case 'bool':
- case 'boolean':
- return isBool;
- case 'undefined':
- default:
- return isUndef;
- }
-};
-
-/**
- * @description Set strong typed object using object proxies and traps
- * @param config
- * @returns {*}
- */
-export const setStrongTypedObject = config => {
- const proxy = {};
- eachProp(config, (prop, key) => (proxy[key] = prop.value));
-
- return new Proxy(proxy, {
- get(target, prop) {
- return target[prop];
- },
- set(target, prop, value) {
- const type = config[prop].type;
- const typeChecker = determineTypeChecker(type);
-
- if (!typeChecker(value)) {
- throw new Error(
- `[Ammo.StrongType] Invalid type. Expected type for field {${prop}} is {${type}}`
- );
- }
-
- target[prop] = value;
- return true;
- }
- });
+ switch (type) {
+ case 'number':
+ return isNum;
+ case 'object':
+ return isObj;
+ case 'null':
+ return isNull;
+ case 'function':
+ return isFunc;
+ case 'array':
+ return isArr;
+ case 'string':
+ return isStr;
+ case 'bool':
+ case 'boolean':
+ return isBool;
+ case 'undefined':
+ default:
+ return isUndef;
+ }
};
/**
@@ -680,14 +652,14 @@ export const setStrongTypedObject = config => {
* @param requiredKeys
*/
export const filterObjectData = (objectData, requiredKeys) => {
- const filteredObject = {};
- eachKey(objectData, (key, value) => {
- if (requiredKeys.indexOf(key) === -1) {
- return false;
- }
- filteredObject[key] = value;
- });
- return filteredObject;
+ const filteredObject = {};
+ eachKey(objectData, (key, value) => {
+ if (requiredKeys.indexOf(key) === -1) {
+ return false;
+ }
+ filteredObject[key] = value;
+ });
+ return filteredObject;
};
/**
@@ -696,11 +668,11 @@ export const filterObjectData = (objectData, requiredKeys) => {
* @param requiredKeys
*/
export const filterArrayOfObjectsData = (arrayData, requiredKeys) => {
- return arrayData.reduce((accumulator, item) => {
- const filteredObject = filterObjectData(item, requiredKeys);
- accumulator.push(filteredObject);
- return accumulator;
- }, []);
+ return arrayData.reduce((accumulator, item) => {
+ const filteredObject = filterObjectData(item, requiredKeys);
+ accumulator.push(filteredObject);
+ return accumulator;
+ }, []);
};
/**
@@ -709,14 +681,14 @@ export const filterArrayOfObjectsData = (arrayData, requiredKeys) => {
* @param requiredKey
*/
export const pluckObjectDataToArray = (objectData, requiredKey) => {
- const filteredArray = [];
- eachKey(objectData, (key, value) => {
- if (requiredKey !== key) {
- return false;
- }
- filteredArray.push(value);
- });
- return filteredArray;
+ const filteredArray = [];
+ eachKey(objectData, (key, value) => {
+ if (requiredKey !== key) {
+ return false;
+ }
+ filteredArray.push(value);
+ });
+ return filteredArray;
};
/**
@@ -725,10 +697,10 @@ export const pluckObjectDataToArray = (objectData, requiredKey) => {
* @param requiredKey
*/
export const pluckArrayOfObjectsDataToArray = (arrayData, requiredKey) => {
- return arrayData.reduce((accumulator, item) => {
- const filteredArray = pluckObjectDataToArray(item, requiredKey);
- return [...accumulator, ...filteredArray];
- }, []);
+ return arrayData.reduce((accumulator, item) => {
+ const filteredArray = pluckObjectDataToArray(item, requiredKey);
+ return [...accumulator, ...filteredArray];
+ }, []);
};
/**
@@ -738,39 +710,39 @@ export const pluckArrayOfObjectsDataToArray = (arrayData, requiredKey) => {
* @returns {*}
*/
export const extractNestedProp = (obj, keysText) => {
- const keys = keysText.split('.');
- const keysLength = keys.length - 1;
- let keysIndex = 0;
- let isValidKey = true;
- let targetObj = Object.assign({}, obj);
- let targetProp;
- let nextTarget;
-
- if (keys.length > 0) {
- while (isValidKey) {
- nextTarget = targetObj[keys[keysIndex]];
-
- // ... check if final target is reached ...
- if (keysIndex === keysLength) {
- // ... extract target prop
- targetProp =
- !isUndef(nextTarget) && !isNull(nextTarget) ? nextTarget : undefined;
- break;
- }
-
- // ... check if next target is not an object ...
- if (!isObj(nextTarget)) {
- // ... cancel sequence
- isValidKey = false;
- break;
- }
-
- targetObj = nextTarget;
- keysIndex++;
- }
- }
-
- return targetProp;
+ const keys = keysText.split('.');
+ const keysLength = keys.length - 1;
+ let keysIndex = 0;
+ let isValidKey = true;
+ let targetObj = Object.assign({}, obj);
+ let targetProp;
+ let nextTarget;
+
+ if (keys.length > 0) {
+ while (isValidKey) {
+ nextTarget = targetObj[keys[keysIndex]];
+
+ // ... check if final target is reached ...
+ if (keysIndex === keysLength) {
+ // ... extract target prop
+ targetProp =
+ !isUndef(nextTarget) && !isNull(nextTarget) ? nextTarget : undefined;
+ break;
+ }
+
+ // ... check if next target is not an object ...
+ if (!isObj(nextTarget)) {
+ // ... cancel sequence
+ isValidKey = false;
+ break;
+ }
+
+ targetObj = nextTarget;
+ keysIndex++;
+ }
+ }
+
+ return targetProp;
};
/**
@@ -781,45 +753,47 @@ export const extractNestedProp = (obj, keysText) => {
* @param direction
*/
export const sortBy = (
- items: any,
- keysText: any,
- type: string = 'string',
- direction: string = 'asc'
+ items: any,
+ keysText: any,
+ type: string = 'string',
+ direction: string = 'asc'
) => {
- return items.sort((a, b) => {
- const aVal = extractNestedProp(a, keysText);
- const bVal = extractNestedProp(b, keysText);
-
- if (isUndef(aVal) || isNull(aVal)) {
- return direction === 'asc' ? -1 : 1;
- }
-
- if (isUndef(bVal) || isNull(bVal)) {
- return direction === 'asc' ? 1 : -1;
- }
-
- if (type === 'string' || type === 'email') {
- if (aVal.toLowerCase() > bVal.toLowerCase()) {
- return direction === 'asc' ? 1 : -1;
- }
- if (aVal.toLowerCase() < bVal.toLowerCase()) {
- return direction === 'asc' ? -1 : 1;
- }
- return 0;
- } else if (type === 'number' || type === 'integer' || type === 'float') {
- if (aVal > bVal) {
- return direction === 'asc' ? 1 : -1;
- }
- if (aVal < bVal) {
- return direction === 'asc' ? -1 : 1;
- }
- return 0;
- } else if (type === 'date') {
- return direction === 'asc'
- ? new Date(aVal) - new Date(bVal)
- : new Date(bVal) - new Date(aVal);
- }
- });
+ return items.sort((a, b) => {
+ const aVal: any = extractNestedProp(a, keysText);
+ const bVal: any = extractNestedProp(b, keysText);
+
+ if (isUndef(aVal) || isNull(aVal)) {
+ return direction === 'asc' ? -1 : 1;
+ }
+
+ if (isUndef(bVal) || isNull(bVal)) {
+ return direction === 'asc' ? 1 : -1;
+ }
+
+ if (type === 'string' || type === 'email') {
+ if (aVal.toLowerCase() > bVal.toLowerCase()) {
+ return direction === 'asc' ? 1 : -1;
+ }
+ if (aVal.toLowerCase() < bVal.toLowerCase()) {
+ return direction === 'asc' ? -1 : 1;
+ }
+ return 0;
+ } else if (type === 'number' || type === 'integer' || type === 'float') {
+ if (aVal > bVal) {
+ return direction === 'asc' ? 1 : -1;
+ }
+ if (aVal < bVal) {
+ return direction === 'asc' ? -1 : 1;
+ }
+ return 0;
+ } else if (type === 'date') {
+ // @ts-ignore
+ const res1 = new Date(aVal) - new Date(bVal);
+ // @ts-ignore
+ const res2 = new Date(bVal) - new Date(aVal);
+ return direction === 'asc' ? res1 : res2;
+ }
+ });
};
/**
@@ -828,34 +802,34 @@ export const sortBy = (
* @returns {*}
*/
export const shape = items => {
- let shapeItems = [...items];
-
- return {
- fetch: () => shapeItems,
- filterByUnique(key) {
- shapeItems = filterByUnique(shapeItems, key);
- return this;
- },
- filterByDuplicate(key, length = 2) {
- shapeItems = filterByDuplicate(shapeItems, key, length);
- return this;
- },
- sortBy({ key, type = 'string', direction = 'asc' }) {
- shapeItems = sortBy(shapeItems, key, type, direction);
- return this;
- },
- reduceTo(key) {
- shapeItems = shapeItems.reduce((accumulator, item) => {
- const prop = extractNestedProp(item, key);
- if (isArr(prop)) {
- return [...accumulator, ...prop];
- } else if (!isUndef(prop) && !isNull(prop)) {
- return [...accumulator, prop];
- }
- }, []);
- return this;
- }
- };
+ let shapeItems = [...items];
+
+ return {
+ fetch: () => shapeItems,
+ filterByUnique(key) {
+ shapeItems = filterByUnique(shapeItems, key);
+ return this;
+ },
+ filterByDuplicate(key, length = 2) {
+ shapeItems = filterByDuplicate(shapeItems, key, length);
+ return this;
+ },
+ sortBy({ key, type = 'string', direction = 'asc' }) {
+ shapeItems = sortBy(shapeItems, key, type, direction);
+ return this;
+ },
+ reduceTo(key) {
+ shapeItems = shapeItems.reduce((accumulator, item) => {
+ const prop = extractNestedProp(item, key);
+ if (isArr(prop)) {
+ return [...accumulator, ...prop];
+ } else if (!isUndef(prop) && !isNull(prop)) {
+ return [...accumulator, prop];
+ }
+ }, []);
+ return this;
+ }
+ };
};
/**
@@ -865,23 +839,23 @@ export const shape = items => {
* @returns {*}
*/
export const filterByUnique = (items, key) =>
- items.reduce((accumulator, item) => {
- const itemProp = extractNestedProp(item, key);
+ items.reduce((accumulator, item) => {
+ const itemProp = extractNestedProp(item, key);
- const isDuplicate =
- accumulator.filter(filteredItem => {
- const prop = extractNestedProp(filteredItem, key);
- return prop === itemProp;
- }).length > 0;
+ const isDuplicate =
+ accumulator.filter(filteredItem => {
+ const prop = extractNestedProp(filteredItem, key);
+ return prop === itemProp;
+ }).length > 0;
- if (isDuplicate) {
- return accumulator;
- }
+ if (isDuplicate) {
+ return accumulator;
+ }
- const modifiedItem = extend({}, item);
- accumulator.push(modifiedItem);
- return accumulator;
- }, []);
+ const modifiedItem = extend({}, item);
+ accumulator.push(modifiedItem);
+ return accumulator;
+ }, []);
/**
* @description Filter by duplicate
@@ -891,14 +865,14 @@ export const filterByUnique = (items, key) =>
* @returns {*}
*/
export const filterByDuplicate = (items, key, duplicateLength = 2) =>
- items.filter(item => {
- const itemProp = extractNestedProp(item, key);
- const duplicatesCount = duplicateLength - 1;
-
- return (
- items.filter(innerItem => {
- const prop = extractNestedProp(innerItem, key);
- return prop === itemProp;
- }).length > duplicatesCount
- );
- });
+ items.filter(item => {
+ const itemProp = extractNestedProp(item, key);
+ const duplicatesCount = duplicateLength - 1;
+
+ return (
+ items.filter(innerItem => {
+ const prop = extractNestedProp(innerItem, key);
+ return prop === itemProp;
+ }).length > duplicatesCount
+ );
+ });