Skip to content

Instantly share code, notes, and snippets.

@felisio
Created November 19, 2018 15:12
Show Gist options
  • Save felisio/12a0561d682d748746b8ddb4f64733b6 to your computer and use it in GitHub Desktop.
Save felisio/12a0561d682d748746b8ddb4f64733b6 to your computer and use it in GitHub Desktop.
Collection of functions for data helper
import {
deburr,
isEmpty,
findIndex,
drop,
pad,
padEnd,
padStart
} from 'lodash';
import moment from 'moment';
// import * as moment from 'moment';
import 'moment/locale/pt-br';
// moment.locale('pt-BR');
import VMasker from '@/dg-lib/vendor/vanilla-masker';
import numeral from 'numeral'
import { mascaraMoeda, formatPhone, formatCnpjCpf } from '../masks/'
import { loadStorage } from '@/helpers/storage/localStorage'
/*
* Sanitize Data
*/
export const sanitize = deburr;
export const sanitizeText = value => sanitize(value);
export const padText = (text, size = 48) => pad(text, size);
export const padEndText = (text, size = 48) => padEnd(text, size);
export const padStarText = (text, size = 48) => padStart(text, size);
export const sanitizeAndLower = value => sanitize(value).toLowerCase();
export const contains = (st, value) => sanitizeAndLower(st).indexOf(sanitizeAndLower(value)) > -1;
export const sanitizeId = id => id.replace(/\[|\]/g, "");
export const stringToMoneyFloat = str => (str)? parseFloat(mascaraMoeda(str,'','.')).toFixed(2) : null;
export const stringToFloat = str => parseFloat(str).toFixed(2);
export const FloatToMaskMoney = flt => (isNegative(flt))? `-${VMasker.toMoney(flt)}` : VMasker.toMoney(flt);
export const SumMoney = (str1, str2) => (parseFloat(str1).toFixed(2) * 1) + (parseFloat(str2).toFixed(2) * 1)
export const StringToCpfCnpj = str => formatCnpjCpf(str, { cpf: '999.999.999-99', cnpj: '99.999.999/9999-99' })
export const convertNegativeToPositive = value => value.replace(/[-]/g, "")
export const sanitizeSpecialCharacters = value => value.replace(/[&\/\\#,$~%.;˜`ˆ+()!@='"`_:*?<>{}]/g, "")
export const sanitizeFloatPoint = value => value.replace(/([aA-zZ&\/\\#,$~%;˜`ˆ+()!@='"`_:*?<>{}])/g, "")
export const convertToEdit = value => JSON.parse( JSON.stringify( value ) )
export const sanitizeToFloatString = (value) => (value.indexOf(",")!= -1) ? value.replace(",", ".") : '0.00'
export const percentage = (num, total) => parseInt(parseInt(num)*100/parseInt(total))
export const isNegative = str => {
const negative = /[-]/g
return negative.test(str)
}
export function arrCopy(arr, offset) {
offset = offset || 0;
const len = Math.max(0, arr.length - offset);
const newArr = new Array(len);
for (let ii = 0; ii < len; ii++) {
newArr[ii] = arr[ii + offset];
}
return newArr;
}
export function parseBoolean(str){
const falsy = /^(?:f(?:alse)?|no?|0+)$/i;
return !falsy.test(str) && !!str
}
export const transformObjFromReportData = (obj, key) => {
const reportModel = { key, params: [] }
for(let key in obj) {
reportModel.params.push({
name: key,
value: obj[key]
})
}
return reportModel
}
export const toCapitalize = (str) => {
return str
.toLowerCase()
.split(" ")
.map(item => item[0].toUpperCase() + item.substring(1))
.join(' ')
}
/*
* Array Data
*/
export const findIndexFromArray = (arrayObj, obj, attr) => findIndex(arrayObj, (o) => { return o[attr] == obj[attr] });
export const findObjFromArray = (arrayObj, idCompare, attr = 'id') => arrayObj.filter((item) => (item[attr] === idCompare) ? item : false)[0]
export const deleteObjFromArray = (arrayObj, obj, attr) => arrayObj.filter(item => item[attr] !== obj[attr]);
export const deleteObjFromArrayById = (arrayObj, obj) => deleteObjFromArray(arrayObj, obj, 'id');
export const insertObjArray = (arrayObj, obj, attr = 'id') => [ ...deleteObjFromArray(arrayObj, obj, attr), obj ];
export const dropArray = (arrayObj, qtd) => drop(arrayObj, qtd);
export const createArrayByBool = (arrayReturn, value, bool) => (bool)? arrayReturn.concat(value) : arrayReturn.filter(item => item !== value)
export const createUniqueArray = arr => [...new Set(arr)];
export const operationValueFromArray = (type, ref = 'value' ) => {
function sumArray (arrayObj){
return arrayObj
.map(item => item[ref])
.reduce((result, item) => SumMoney(result, item).toFixed(2), 0)
}
switch(type){
case 'sum':
return sumArray
}
}
export function cloneDeep(value) {
// verifica se for um array e cria a partir desse array
if (Array.isArray(value)) {
return value.map(function (item) { return cloneDeep(item); });
}
// se for um objeto cria outro a partir do primeiro a ser clonado
if (value !== null && typeof value === 'object') {
var nextValue = {};
for (var key in value) {
if (value.hasOwnProperty(key)) {
nextValue[key] = cloneDeep(value[key]);
}
}
return nextValue;
}
// caso não seja nenhum do dois ele ja é um objeto mutavel é so retornar ele mesmo
return value;
}
/*
* Date Hour format
*/
export const isDateValid = (date) => moment(date, 'DD/MM/YYYY').isValid();
export const dateToTimestamp = (date) => {
if(!isDateValid(date)){ return false; }
if(typeof date === 'object') {
return parseInt(moment(new Date(date)).format('x'));
}
const arrayDate = date.split('/');
const resultDate = moment({ y: parseInt(arrayDate[2]), M: parseInt(arrayDate[1] -1), d: parseInt(arrayDate[0]) }).format('x');
return parseInt(resultDate);
};
export const getBirthdayToTimeStamp = (stamp) => moment().diff(new Date(stamp), 'years', false)
export const timestampToDate = (stamp, format='DD/MM/YYYY') => {
return moment(new Date(stamp), format, 'pt-BR').format(format);
};
export const timestampToDateHour = (stamp) => {
return moment(new Date(stamp), 'DD/MM/YYYY', 'pt-BR').format('DD/MM/YYYY, H:mm:ss');
};
export const timestampToSimpleDateHour = (stamp) => {
return moment(new Date(stamp), 'DD/MM', 'pt-BR').format('DD/MM HH:mm');
};
export const timestampToHour = (stamp, format='H:mm:ss') => {
return moment(new Date(stamp), 'DD/MM/YYYY', 'pt-BR').format(format);
};
export const getDate = (date ,format= 'DD/MM/YYYY') => moment(date, 'DD/MM/YYYY', 'pt-BR').format(format);
export const getTodayDate = (format= 'DD/MM/YYYY') => moment(new Date(), 'DD/MM/YYYY', 'pt-BR').format(format);
export const getMonthRef = (date = new Date(), format= 'MM/YYYY') => moment(date, 'DD/MM/YYYY', 'pt-BR').format(format);
export const getDaysInMonth = (date = new Date()) => moment(date, 'DD/MM/YYYY', 'pt-BR').daysInMonth()
export const addDayInDate = (date, days=1) => moment(date, 'DD/MM/YYYY', 'pt-BR').add(days, 'days').format('DD/MM/YYYY');
export const subtractDayInDate = (date, days=1) => moment(date, 'DD/MM/YYYY', 'pt-BR').subtract(days, 'days').format('DD/MM/YYYY');
export const addPeriod = (date, period = 'days' ,days = 1, format = 'DD/MM/YYYY') => moment(date, 'DD/MM/YYYY', 'pt-BR').add(days, period).format(format);
export const subPeriod = (date, period = 'days' ,days = 1, format = 'DD/MM/YYYY') => moment(date, 'DD/MM/YYYY', 'pt-BR').subtract(days, period).format(format);
export const getDateByMonth = (initDate, months) => moment(initDate, 'DD/MM/YYYY', 'pt-BR').add(months, 'months').format('DD/MM/YYYY');
export const getPeriodStart = (period = 'week' ,format = 'DD/MM/YYYY', date = new Date()) =>
moment(moment(date, 'DD/MM/YYYY', 'pt-BR').startOf(period), 'DD/MM/YYYY', 'pt-BR').format(format)
export const getPeriodEnd = (period = 'week' ,format = 'DD/MM/YYYY', date = new Date()) =>
moment(moment(date, 'DD/MM/YYYY', 'pt-BR').endOf(period), 'DD/MM/YYYY', 'pt-BR').format(format)
export const getWeekString = (date = new Date()) =>
`
${moment(moment(date, 'DD/MM/YYYY', 'pt-BR').startOf('week'), 'DD/MM/YYYY', 'pt-BR').format('DD MMM')}
à
${moment(moment(date, 'DD/MM/YYYY', 'pt-BR').endOf('week'), 'DD/MM/YYYY', 'pt-BR').format('DD MMM')}
`
export const getDaysBetweenDates = (dateFrom, dateTo) => {
const from = moment(dateFrom, 'DD/MM/YYYY', 'pt-BR')
const to = moment(dateTo, 'DD/MM/YYYY', 'pt-BR')
//return parseInt(to.diff(from, 'days'))
return Math.abs(parseInt(moment.duration(from.diff(to)).asDays()))
}
export const getMonthsBetweenDates = (dateFrom, dateTo) => {
const from = moment(dateFrom, 'DD/MM/YYYY', 'pt-BR')
const to = moment(dateTo, 'DD/MM/YYYY', 'pt-BR')
return parseInt(to.diff(from, 'months'))
}
export const unformatHour = hour => (/^(([0-1]{1}[0-9]{1}|20|21|22|23):[0-5]{1}[0-9]{1})$/.test(hour))? hour.replace(/:/g, "") : hour;
export const formatHour = hour => {
if(hour === null || hour === ''){ return '' }
const stringHour = hour.toString()
if(stringHour.length === 3){
return `0${stringHour[0]}:${stringHour[1]}${stringHour[2]}`;
}else if(stringHour.length === 4){
return `${stringHour[0]}${stringHour[1]}:${stringHour[2]}${stringHour[3]}`;
}
};
export const formatHourArrayObj = (arrayObj) => {
return arrayObj.map(item => {
item.times = item.times.map(time => {
time.startTime = formatHour(time.startTime)
time.endTime = formatHour(time.endTime)
return time
})
return item
})
};
export const unformatHourArrayObj = (arrayObj) => {
return arrayObj.map(item => {
item.times = item.times.map(time => {
time.startTime = parseInt(unformatHour(time.startTime))
time.endTime = parseInt(unformatHour(time.endTime))
return time
})
return item
})
};
export const qntDayOfMonth = (date) => {
const arrayDate = date.split('/')
const mes = parseInt(arrayDate['1']) -1;
const ano = parseInt(arrayDate['2']);
let bissexto;
if((ano%4) == 0 && (ano%100)!=0 ||(ano%400)==0){
bissexto = 29;
}else{
bissexto = 28;
}
const meses = new Array(31,bissexto,31,30,31,30,31,31,30,31,30,31);
const qnt = meses[mes];
return qnt;
}
/*
* Tree View Data
*/
export const createTreeView = (arrayData) => {
const insertChildren = (item) => {
arrayData.forEach(obj => {
if(item.id === obj.parentId) {
if(item.hasOwnProperty('children')){
item.children = deleteObjFromArrayById(item.children, obj);
item.children.push(obj)
}else{
item.children = []
item.children.push(obj)
}
item.children.map(insertChildren)
}
});
return item;
}
const newArray = arrayData.map(insertChildren).filter((item) => {
return (!item.parentId) ? true : false
})[0]
return newArray;
};
export const createTree = (arrayData, treeViewCheckList = []) => {
const insertChildren = (item) => {
arrayData.forEach(obj => {
if(item.id === obj.parentId) {
if(item.hasOwnProperty('children')){
item.children = deleteObjFromArrayById(item.children, obj);
item.children.push(obj)
}else{
item.children = []
item.children.push(obj)
}
item.children.map(insertChildren)
}
item.checked = (treeViewCheckList.find(id => id === item.id))? true : false
});
return item;
}
const newArray = arrayData.map(insertChildren).filter((item) => {
return (!item.parentId) ? true : false
})
return newArray;
};
/*
* Permissions
* */
export const verifyPermission = (keyPermission) => {
if(!keyPermission) { return true }
const permissions = loadStorage('polisystem_storage_group_permissions')
if(permissions && permissions.length) {
const hasPermission = permissions.find(item => item === keyPermission)
return (hasPermission)? hasPermission : false
}
return false
}
/**
* Styles
*/
export function parseStyle(propertiesObj) {
const arrayStyles = []
for (let prop in propertiesObj) {
arrayStyles.push(`${sanitizeProp(prop)}:${propertiesObj[prop]}`)
}
return arrayStyles.join(';')
}
const sanitizeProp = (prop) => prop.replace(/([A-Z])/g, '-$1').toLowerCase()
/**
* Days Difference Calculator
*/
export function daysDifCalc(initDate, finalDate) {
if(!finalDate) { finalDate = new Date() }
const _MS_PER_DAY = 1000 * 60 * 60 * 24
initDate = new Date(initDate)
// Discard the time and time-zone information.
const utc1 = Date.UTC(initDate.getFullYear(), initDate.getMonth(), initDate.getDate());
const utc2 = Date.UTC(finalDate.getFullYear(), finalDate.getMonth(), finalDate.getDate());
return Math.floor((utc2 - utc1) / _MS_PER_DAY);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment