index.js 4.18 KB
Newer Older
quynhquang400@gmail.com's avatar
quynhquang400@gmail.com committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
import AsyncStorage from '@react-native-async-storage/async-storage';
import moment from 'moment';
import {Linking} from 'react-native';
import config from '../config';
const storeData = async (storageKey, value) => {
  try {
    const jsonValue = JSON.stringify(value);
    await AsyncStorage.setItem(storageKey, jsonValue);
  } catch (e) {
    // saving error
  }
};

const getData = async storageKey => {
  try {
    const jsonValue = await AsyncStorage.getItem(storageKey);
quynhquang400@gmail.com's avatar
quynhquang400@gmail.com committed
17
    return jsonValue != null ? JSON.parse(jsonValue) : null;
quynhquang400@gmail.com's avatar
quynhquang400@gmail.com committed
18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184
  } catch (e) {
    // error reading value
  }
};
const removeData = async storageKey => {
  try {
    await AsyncStorage.removeItem(storageKey);
  } catch (e) {
    // error reading value
  }
};

// const startTime = new Date('2023-03-16T12:55:00+07:00');
const calculateElapsedSeconds = (eventDate, eventTime) => {
  const eventDateTime = moment(
    `${eventDate.split('T')[0]}T${eventTime ?? '13:00:00'}`,
  );
  const now = moment();
  const elapsedSeconds = Math.max(eventDateTime.diff(now, 'seconds'), 0) - 300;
  return elapsedSeconds <= 0 ? 0 : elapsedSeconds;
};

/**
 * Nested Object or Array data value retriever
 * @param source
 * @param variables {string}
 * @param fallbackValue {any}
 * @param allowNull
 * @returns {any|boolean|string}
 */
const getValues = (
  source,
  variables = '',
  fallbackValue,
  allowNull = false,
) => {
  const targetValueHierarchy = (variables || '')
    .toString()
    .replace(/[[\]]/g, '.')
    .split('.')
    .filter(key => key !== '');

  if (source === null && allowNull && targetValueHierarchy.length === 0) {
    return null;
  }

  // Check for string type because string is subtype of Array
  // Don't worry, if the data type not an object or array will fail after that.
  if (!source || ['string, boolean'].includes(typeof source)) {
    return fallbackValue;
  }

  // Retain data type cause data type is dynamic
  let result = Object.assign(source);

  for (let i = 0; i < targetValueHierarchy.length; i++) {
    result = result[targetValueHierarchy[i]];

    if (result === undefined) {
      break;
    }

    if (result === null && i !== targetValueHierarchy.length - 1) {
      result = undefined;
      break;
    }
  }

  if (result === null) {
    return allowNull ? result : fallbackValue;
  }

  return result !== undefined ? result : fallbackValue;
};

const formatLinkYoutube = url => {
  var regExp =
    /^.*((youtu.be\/)|(v\/)|(\/u\/\w\/)|(embed\/)|(watch\?))\??v?=?([^#&?]*).*/;
  var match = url.match(regExp);
  return match && match[7].length == 11 ? match[7] : '';
};

const handleOpenUrl = async url => {
  // Checking if the link is supported for links with custom URL scheme.
  const supported = await Linking.canOpenURL(url);
  if (supported) {
    // Opening the link with some app, if the URL scheme is "http" the web link should be opened
    // by some browser in the mobile
    await Linking.openURL(url);
  }
};
const formatMonthVietNamLanguage = month => {
  const months = [
    {
      en: 'January',
      vi: 'Tháng 1',
    },
    {
      en: 'February',
      vi: 'Tháng 2',
    },
    {
      en: 'March',
      vi: 'Tháng 3',
    },
    {
      en: 'April',
      vi: 'Tháng 4',
    },
    {
      en: 'May',
      vi: 'Tháng 5',
    },
    {
      en: 'June',
      vi: 'Tháng 6',
    },
    {
      en: 'July',
      vi: 'Tháng 7',
    },
    {
      en: 'August',
      vi: 'Tháng 8',
    },
    {
      en: 'September',
      vi: 'Tháng 9',
    },
    {
      en: 'October',
      vi: 'Tháng 10',
    },
    {
      en: 'November',
      vi: 'Tháng 11',
    },
    {
      en: 'December',
      vi: 'Tháng 12',
    },
  ];
  const viMonth = months.filter(item => item.en === month);
  return viMonth[0].vi;
};

const formatCurrency = price => {
  if (!price || !Number(price)) return;
  return price.toLocaleString('vi', {style: 'currency', currency: 'VND'});
};
const getCategoryNotification = category => {
  return Object.keys(config.categoryNotification).find(el => el === category);
};

const Utils = {
  storeData,
  getData,
  removeData,
  calculateElapsedSeconds,
  getValues,
  formatLinkYoutube,
  handleOpenUrl,
  formatMonthVietNamLanguage,
  formatCurrency,
  getCategoryNotification,
};
export default Utils;