Format.ts 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240
  1. import { BYTE_UNITS } from '../consts/Util';
  2. import {
  3. CreateFieldType,
  4. DataTypeEnum,
  5. Field,
  6. } from '../pages/collections/Types';
  7. /**
  8. * transform large capacity to capacity in b.
  9. * @param capacity like: 10g, 10gb, 10m, 10mb, 10k, 10kb, 10b,
  10. * @return number
  11. */
  12. export const parseByte = (capacity?: string | number): number => {
  13. // if it's number return it
  14. if (!isNaN(Number(capacity))) {
  15. return capacity as number;
  16. }
  17. // capacity is '' or 0 or undefined
  18. if (!capacity) {
  19. return 0;
  20. }
  21. let lowerCapacity = (capacity as string).toLowerCase();
  22. const units = BYTE_UNITS;
  23. const isAlpha = /[a-zA-Z]/;
  24. const lastStr = lowerCapacity.charAt(lowerCapacity.length - 1);
  25. const secLastStr = lowerCapacity.charAt(lowerCapacity.length - 2);
  26. // if last two alpha is string, like: mb gb kb.
  27. // delete last alpha b
  28. if (isAlpha.test(lastStr) && isAlpha.test(secLastStr)) {
  29. lastStr === 'b' &&
  30. (lowerCapacity = lowerCapacity.slice(0, lowerCapacity.length - 1));
  31. }
  32. const suffix = lowerCapacity.charAt(lowerCapacity.length - 1);
  33. const digitsPart = lowerCapacity.slice(0, lowerCapacity.length - 1);
  34. if (units[suffix]) {
  35. return Number(digitsPart) * units[suffix];
  36. }
  37. throw new Error(
  38. 'The specified value for memory ({0}) should specify the units. The postfix should be one of the `b` `k` `m` `g` characters'
  39. );
  40. };
  41. /**
  42. *
  43. * @param search ?name=czz&age=18
  44. * @returns {name:'czz',age:'18'}
  45. */
  46. export const parseLocationSearch = (search: string) => {
  47. const pairs = search.substring(1).split('&');
  48. let obj: any = {};
  49. for (let i in pairs) {
  50. if (pairs[i] === '') continue;
  51. const pair = pairs[i].split('=');
  52. obj[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1]);
  53. }
  54. return obj;
  55. };
  56. export const getEnumKeyByValue = (enumObj: any, enumValue: any) => {
  57. const match = Object.entries(enumObj).find(
  58. ([, value]) => value === enumValue
  59. );
  60. if (match) {
  61. const [key] = match;
  62. return key;
  63. }
  64. return '--';
  65. };
  66. /**
  67. *
  68. * @param obj e.g. {name: 'test'}
  69. * @returns key value pair, e.g. [{key: 'name', value: 'test'}]
  70. */
  71. export const getKeyValuePairFromObj = (
  72. obj: { [key in string]: any }
  73. ): { key: string; value: any }[] => {
  74. const pairs: { key: string; value: string }[] = Object.entries(obj).map(
  75. ([key, value]) => ({
  76. key,
  77. value: value as string,
  78. })
  79. );
  80. return pairs;
  81. };
  82. /**
  83. * @param pairs e.g. [{key: 'key', value: 'value'}]
  84. * @returns object, e.g. {key: value}
  85. */
  86. export const getObjFromKeyValuePair = (
  87. pairs: { key: string; value: any }[]
  88. ): { [key in string]: any } => {
  89. const obj = pairs.reduce((acc, cur) => {
  90. acc[cur.key] = cur.value;
  91. return acc;
  92. }, {} as { [key in string]: any });
  93. return obj;
  94. };
  95. export const getKeyValueListFromJsonString = (
  96. json: string
  97. ): { key: string; value: string }[] => {
  98. try {
  99. const obj = JSON.parse(json);
  100. const pairs = getKeyValuePairFromObj(obj);
  101. return pairs;
  102. } catch (err) {
  103. throw err;
  104. }
  105. };
  106. // BinarySubstructure includes Superstructure and Substructure
  107. export const checkIsBinarySubstructure = (metricLabel: string): boolean => {
  108. return metricLabel === 'Superstructure' || metricLabel === 'Substructure';
  109. };
  110. export const getCreateFieldType = (config: Field): CreateFieldType => {
  111. if (config.is_primary_key) {
  112. return 'primaryKey';
  113. }
  114. if (config.isDefault) {
  115. return 'defaultVector';
  116. }
  117. const vectorTypes = [DataTypeEnum.BinaryVector, DataTypeEnum.FloatVector];
  118. if (vectorTypes.includes(config.data_type)) {
  119. return 'vector';
  120. }
  121. return 'number';
  122. };
  123. // Trim the address
  124. export const formatAddress = (address: string): string =>
  125. address.trim().replace(/(http|https):\/\//, '');
  126. export const formatByteSize = (
  127. size: number,
  128. capacityTrans: { [key in string]: string }
  129. ): { value: string; unit: string; power: number } => {
  130. const power = Math.round(Math.log(size) / Math.log(1024));
  131. let unit = '';
  132. switch (power) {
  133. case 1:
  134. unit = capacityTrans.kb;
  135. break;
  136. case 2:
  137. unit = capacityTrans.mb;
  138. break;
  139. case 3:
  140. unit = capacityTrans.gb;
  141. break;
  142. case 4:
  143. unit = capacityTrans.tb;
  144. break;
  145. case 5:
  146. unit = capacityTrans.pb;
  147. break;
  148. default:
  149. unit = capacityTrans.b;
  150. break;
  151. }
  152. const byteValue = size / 1024 ** power;
  153. return {
  154. value: byteValue.toFixed(2),
  155. unit,
  156. power,
  157. };
  158. };
  159. // generate a sting like 20.22/98.33MB with proper unit
  160. export const getByteString = (
  161. value1: number,
  162. value2: number,
  163. capacityTrans: { [key in string]: string }
  164. ) => {
  165. if (!value1 || !value2) return `0${capacityTrans.b}`;
  166. const formatValue1 = formatByteSize(value1, capacityTrans);
  167. const formatValue2 = value2 / 1024 ** formatValue1.power;
  168. return `${formatValue1.value}/${formatValue2.toFixed(2)} ${
  169. formatValue1.unit
  170. }`;
  171. };
  172. /**
  173. * time: 2022-02-15 07:03:32.2981238 +0000 UTC m=+2.434915801
  174. * @returns 2022-02-15 07:03:32
  175. */
  176. export const formatSystemTime = (time: string): string => {
  177. return time.split('.')[0] || '';
  178. };
  179. /**
  180. * When number is larger than js max number, transform to string by BigInt.
  181. * @param bigNumber
  182. * @returns
  183. */
  184. export const formatUtcToMilvus = (bigNumber: number) => {
  185. const milvusTimeStamp = BigInt(bigNumber) << BigInt(18);
  186. return milvusTimeStamp.toString();
  187. };
  188. /**
  189. * Convert headers and rows to csv string.
  190. * @param headers csv headers: string[]
  191. * @param rows csv data rows: {[key in headers]: any}[]
  192. * @returns csv string
  193. */
  194. export const generateCsvData = (headers: string[], rows: any[]) => {
  195. const rowsData = rows.reduce((prev, item: any[]) => {
  196. headers.forEach((colName: any, idx: number) => {
  197. const val = item[colName];
  198. if (typeof val === 'string') {
  199. prev += val;
  200. } else if (typeof val === 'object') {
  201. // Use double quote to ensure csv display correctly
  202. prev += `"${JSON.stringify(val)}"`;
  203. } else {
  204. prev += `${val}`;
  205. }
  206. if (idx === headers.length - 1) {
  207. prev += '\n';
  208. } else {
  209. prev += ',';
  210. }
  211. });
  212. return prev;
  213. }, '');
  214. return headers.join(',') + '\n' + rowsData;
  215. };