import { existsSync } from 'fs'; import { uniqWith } from 'lodash'; import os from 'os'; import ProgressBar from 'progress'; export function objectsUniqByKey< T extends { [key: string]: number | string; } >(data: T[], key: string): T[] { return uniqWith(data, (item1: T, item2: T) => item1[key] === item2[key]); } export function mergeArray(...arr: Array>): T[] { let res: T[] = []; arr.forEach((item) => { res = [...res, ...item]; }); return res; } /** * 字节转换并加上单位 * 1024 => 1 KB * @param bytes 字节 */ export function byteConvert(bytes: number): string { if (bytes === 0) return '0 B'; const k = 1024; const sizes = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']; const i = Math.floor(Math.log(bytes) / Math.log(k)); return (bytes / k ** i).toFixed(2) + ' ' + sizes[i]; } export function getProgressBarInstance(tip: string, total: number): ProgressBar { return new ProgressBar(`${tip}[:bar] :current/:total :percent :etas`, { total, width: 30, complete: '=', incomplete: ' ', }); } export function promiseQueue(tasks: (() => Promise)[]): Promise { return tasks.reduce((prev, cur) => prev.then(() => cur().then()), Promise.resolve()); } export function checkConf({ inputDirPath, outputDirPath, }: { inputDirPath: string; outputDirPath: string; }): void { if (!existsSync(inputDirPath)) { throw new Error(`inputDirPath: ${inputDirPath} 不存在`); } if (!existsSync(outputDirPath)) { throw new Error(`outputDirPath: ${outputDirPath} 不存在`); } } export const isWindows = (): boolean => { return os.platform().indexOf('win') === 0 || os.type().indexOf('Windows') >= 0; };