Skip to content

Instantly share code, notes, and snippets.

@felisio
Created October 10, 2018 11:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save felisio/0e1409ea8c6385704854ea966ca30f39 to your computer and use it in GitHub Desktop.
Save felisio/0e1409ea8c6385704854ea966ca30f39 to your computer and use it in GitHub Desktop.
Helpers Collection
export function dateTimeFormatter (date ,format) {
// date: format:'yyyy-MM-dd hh:mm:ss'
if (!date || date == "") {
return ""
}
if (typeof date === "string") {
var mts = date.match(/(\/Date\((\d+)\)\/)/)
if (mts && mts.length >= 3) {
date = parseInt(mts[2])
}
}
date = new Date(date)
if (!date || date.toUTCString() == "Invalid Date") {
return ""
}
var map = {
"M": date.getMonth() + 1,
"d": date.getDate(),
"h": date.getHours(),
"m": date.getMinutes(),
"s": date.getSeconds(),
"q": Math.floor((date.getMonth() + 3) / 3),
"S": date.getMilliseconds()
}
format = format.replace(/([yMdhmsqS])+/g, function(all, t){
var v = map[t]
if(v !== undefined){
if(all.length > 1){
v = '0' + v
v = v.substr(v.length-2)
}
return v
}
else if(t === 'y'){
return (date.getFullYear() + '').substr(4 - all.length)
}
return all
})
return format
}
export function isEqualDateStr (dateStr1, dateStr2) {
let dateArr1 = dateStr1.split('/')
let dateArr2 = dateStr2.split('/')
if (parseInt(dateArr1[0], 10) !== parseInt(dateArr2[0], 10)) {
return false
}
if (parseInt(dateArr1[1], 10) !== parseInt(dateArr2[1], 10)) {
return false
}
if (parseInt(dateArr1[2], 10) !== parseInt(dateArr2[2], 10)) {
return false
}
return true
}
export const calendarLabel = {
dayNames: ["Dom", "Seg", "Ter", "Qua", "Qui", "Sex", "Sáb"],
monthNames: ["Janeiro", "Fevereiro", "Março", "Abril", "Maio", "Junho", "Julho", "Agosto", "Setembro", "Outubro", "Novembro", "Dezembro"],
format : 'MM/yyyy',
fullFormat: 'dd/MM/yyyy',
dayEventsTitle: 'Todos os eventos',
notHaveEvents: 'Nenhum evento'
}
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);
}
import { sanitizeToFloatString } from './index'
const tableIMC = [
{"min": 0, "max": 17, "msg": "Aluno está muito abaixo do seu peso ideal!"},
{"min": 17, "max": 18.5, "msg": "Aluno está abaixo do seu peso ideal!"},
{"min": 18.5, "max": 25, "msg": "Aluno está em seu peso ideal!"},
{"min": 25, "max": 30, "msg": "Sobrepeso - Aluno está acima do seu peso ideal."},
{"min": 30, "max": 35, "msg": "Obesidade - grau I"},
{"min": 35, "max": 40, "msg": "Obesidade - grau II (severa)"},
{"min": 40, "max": 1000, "msg": "Obesidade - grau III (môrbida)"}
]
const findImcResult = (imc) => tableIMC.filter(item => ( (parseFloat(imc) > parseFloat(item.min)) && (parseFloat(imc) <= parseFloat(item.max)) ) ? true : false)[0].msg
const convertCmToM = (height) => parseFloat(parseInt(height) / 100).toFixed(2)
export const calcImc = (weight, height) => {
let resultCalc = 0;
let weightFloat = parseFloat(weight);
let heightFloat = parseFloat(height);
if(heightFloat > 100){ heightFloat = heightFloat / 100 }
resultCalc = weightFloat / (heightFloat * heightFloat)
return resultCalc.toFixed(2).replace(".",",");
}
const calcBestWeightMin = (height) => (18.5 * parseFloat(height) * parseFloat(height)).toFixed(0)
const calcBestWeightMax = (height) => (25 * parseFloat(height) * parseFloat(height)).toFixed(0)
export const calculateIMC = (weight, height) => {
if(weight == "" || height == "" ){ return false }
const convertWeight = sanitizeToFloatString(weight)
const convertHeight = convertCmToM(height)
/* calcula o IMC */
const imc = calcImc(convertWeight, convertHeight)
/* busca intervalo na tabela */
const message = findImcResult(imc)
/* calcula resultado ideal */
const bestWeightMin = calcBestWeightMin(convertHeight)
const bestWeightMax = calcBestWeightMax(convertHeight)
return {
imc,
message,
bestWeightMin,
bestWeightMax
}
}
export const loadStorage = (stateName) => {
try {
const serializedState = localStorage.getItem(stateName);
if(serializedState === null){
return undefined;
}
return JSON.parse(serializedState);
} catch (e) {
return undefined;
}
};
export const saveStorage = (stateName, state) => {
try {
const serializedState = JSON.stringify(state);
localStorage.setItem(stateName, serializedState);
} catch (e) {
console.error('Erro ao gravar no storage:', e);
}
};
export const removeStorage = (stateName) => {
try {
localStorage.removeItem(stateName);
} catch (e) {
console.error('Erro ao remover no storage:', e);
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment