aboutsummaryrefslogtreecommitdiffstats
path: root/src/jsUtils.ts
blob: 0befb8d5601dd96ef3dc823b00c939ec67af6437 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
export const ifUndefined = <T>(
  source: undefined | null | T,
  defaultValue: T,
): T => source ?? defaultValue;

export const convertToJSON = (data?: string | any | null) =>
  data && typeof data === 'string' && data.length > 0 ? JSON.parse(data) : data;

export const cleanseJSObject = (data?: any | null) =>
  JSON.parse(JSON.stringify(data));

export const isArrowUpKeyPress = (key: string) => key === 'ArrowUp';
export const isArrowDownKeyPress = (key: string) => key === 'ArrowDown';
export const isEnterKeyPress = (key: string) => key === 'Enter';
export const isEscapeKeyPress = (key: string) => key === 'Escape';
export const isShiftKeyPress = (key: string) => key === 'Shift';

export const safeParseInt = (text?: string | number | null) => {
  if (text === undefined || text === null) {
    return 0;
  }

  // Parse number to integer
  // This will correct errors that recipes may introduce, e.g.
  // by sending a String instead of an integer
  const parsedNumber = Number.parseInt(text.toString(), 10);
  const adjustedNumber = Number.isNaN(parsedNumber) ? 0 : parsedNumber;
  return Math.max(adjustedNumber, 0);
};

export const acceleratorString = (
  index: number,
  keyCombo: string,
  prefix: string = '(',
  suffix: string = ')',
) => (index <= 10 ? `${prefix}${keyCombo}+${index % 10}${suffix}` : '');

export const removeNewLines = (input: string): string =>
  input.replaceAll(/\r?\n|\r/g, '');