UNPKG

@open-tender/utils

Version:

A library of utils for use with Open Tender applications that utilize our cloud-based Order API.

206 lines (205 loc) 7.48 kB
export const isString = (str) => { return typeof str === 'string'; }; export const isObject = (obj) => { return typeof obj === 'object' && obj !== null; }; export const isEmpty = (obj) => { return (!obj || (obj.constructor === Object && Object.entries(obj).length === 0)); }; export const isNum = (s) => /^\d+$/.test(s); /** * @deprecated please use `containsAll` or `containsAny` instead * @returns true if first argument contains any of the values in the second argument */ export const contains = (arr, values) => { return values.filter(i => arr.includes(i)).length > 0; }; /** * @returns true if first argument contains any of the values in the second argument */ export const containsAny = (arr, values) => { return values.length === 0 || values.filter(i => arr.includes(i)).length > 0; }; /** * @returns true if first argument contains all of the values of the second argument */ export const containsAll = (arr, values) => { return values.filter(i => arr.includes(i)).length === values.length; }; // https://gist.github.com/mathewbyrne/1280286 export const slugify = (text) => { return text .toString() .toLowerCase() .replace('_', '-') // replace _ with - .replace(/\s+/g, '-') // Replace spaces with - .replace(/[^\w-]+/g, '') // Remove all non-word chars .replace(/--+/g, '-') // Replace multiple - with single - .replace(/^-+/, '') // Trim - from start of text .replace(/-+$/, ''); // Trim - from end of text }; export const stripTags = (s) => s.replace(/(<([^>]+)>)/gi, '').replace('&amp;', '&'); export const serialize = (obj) => { const str = []; for (const p in obj) if (Object.prototype.hasOwnProperty.call(obj, p)) { str.push(encodeURIComponent(p) + '=' + encodeURIComponent(obj[p])); } return str.join('&'); }; export const capitalize = (s) => { if (!s || !s.length) return ''; return s.charAt(0).toUpperCase() + s.slice(1).toLowerCase(); }; export const cleanPhone = (phone) => { if (!phone) return ''; let p = phone.replace(/\D/g, ''); if (p.length > 11) return phone; p = p.length === 11 && p[0] === '1' ? p.slice(1, 11) : p; p = p.length === 10 ? `${p.slice(0, 3)}-${p.slice(3, 6)}-${p.slice(6, 10)}` : p; return p; }; export const makePhone = (phone) => { if (!phone) return ''; const p = phone.replace(/\D/g, ''); if (p.length > 6) { return `${p.slice(0, 3)}-${p.slice(3, 6)}-${p.slice(6, 10)}`; } else if (p.length > 3) { return `${p.slice(0, 3)}-${p.slice(3, 6)}`; } return p; }; export const validatePhone = (phone) => { var _a; if (!phone) return false; return ((_a = phone.match(/\d/g)) === null || _a === void 0 ? void 0 : _a.length) === 10; }; export const makeBirthDate = (birthDate) => { if (!birthDate) return null; const b = birthDate.replace(/\D/g, ''); if (b.length > 4) { return `${b.slice(0, 2)}/${b.slice(2, 4)}/${b.slice(4, 8)}`; } else if (b.length > 2) { return `${b.slice(0, 2)}/${b.slice(2, 4)}`; } return b; }; export const slashesToDashes = (birthDate) => { if (!birthDate) return null; const parts = birthDate.split('/'); return `${parts[2] || ''}-${parts[0] || ''}-${parts[1] || ''}`; }; export const dashesToSlashes = (birthDate) => { if (!birthDate) return null; const parts = birthDate.split('-'); return `${parts[1] || ''}/${parts[2] || ''}/${parts[0] || ''}`; }; export const validateEmail = (email) => { const re = // eslint-disable-next-line no-useless-escape /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; return re.test(email); }; export const checkEmpty = (data) => { if (isEmpty(data)) return true; return Object.values(data).filter(i => !i).length > 0; }; export const checkGuestData = (data, email) => { const { first_name, last_name, phone } = data; const guestData = { first_name, last_name, phone, email }; const validPhone = phone ? validatePhone(phone) || null : null; const guestIncomplete = checkEmpty(Object.assign(Object.assign({}, guestData), { phone: validPhone })); return { guestData, guestIncomplete }; }; export const checkNotFound = (errors) => { const errMsg = errors ? errors.email || errors.form : null; if (!errMsg) return null; return (errMsg.includes('not associated') || errMsg.includes('Account not found')); }; export const makeRandomNumberString = () => Math.floor(Math.random() * 1000000000).toString(); export const getWidth = () => { return Math.max(document.body.scrollWidth, document.documentElement.scrollWidth, document.body.offsetWidth, document.documentElement.offsetWidth, document.documentElement.clientWidth); }; export const getHeight = () => { return Math.max(document.body.scrollHeight, document.documentElement.scrollHeight, document.body.offsetHeight, document.documentElement.offsetHeight, document.documentElement.clientHeight); }; export const makeImageMap = (images) => { const imagesMap = images .filter(i => i.url) .reduce((obj, i) => (Object.assign(Object.assign({}, obj), { [i.type]: i.url })), {}); return imagesMap; }; export const makeImageUrl = (images, isMobile) => { var _a; return (_a = images.find(i => i.type === (isMobile ? 'SECONDARY_IMAGE' : 'FEATURED_IMAGE'))) === null || _a === void 0 ? void 0 : _a.url; }; export const makeSlides = (items, isMobile) => { if (!items || !items.length) return null; return items.map(i => (Object.assign(Object.assign({}, i), { imageUrl: makeImageUrl(i.images, isMobile) }))); }; export const displayPrice = (price) => { return parseFloat(price).toFixed(2); }; export const addCommas = (x, d) => { const valueToReplace = d === undefined ? x.toString() : x.toFixed(d); return valueToReplace.replace(/\B(?=(\d{3})+(?!\d))/g, ','); }; export const formatQuantity = (n) => { return addCommas(parseFloat(n), 0); }; export const formatPercentage = (n, d) => { return addCommas(parseFloat(n), d); }; export const formatDollars = (str, space = '', decimals = 2) => { const floatPrice = parseFloat(str); return floatPrice < 0 ? `($${addCommas(Math.abs(floatPrice), decimals)})` : `$${addCommas(floatPrice, decimals)}${space}`; }; export const convertStringToArray = (str) => { return str ? str .split(',') .map(i => i.trim()) .filter(i => i.length) : []; }; export const hasEntities = (reducer) => { if (!reducer) return false; const { entities, loading, error } = reducer; if (!entities) return false; if (loading === 'pending' && !entities.length) return false; return !error && entities.length; }; export const range = (start, end, step = 1) => { if (typeof end === 'undefined') { end = start; start = 0; } const length = Math.max(Math.ceil((end - start) / step), 0); return Array.from({ length }, (_, index) => start + index * step); }; export const sample = (collection) => { if (collection.length === 0) return undefined; const randomIndex = Math.floor(Math.random() * collection.length); return collection[randomIndex]; };