Skip to content

Instantly share code, notes, and snippets.

@gughog
Last active July 30, 2020 17:23
Show Gist options
  • Save gughog/dc44c580dee4f310e09195a6dddd909e to your computer and use it in GitHub Desktop.
Save gughog/dc44c580dee4f310e09195a6dddd909e to your computer and use it in GitHub Desktop.
Javascript Utility Functions

Javascript Utility Functions

This is a collection of utility functions (work in progress) that do a range of things. If you have some to contribute, please, contribute! 😄

Current:

  • Finding missing objects/elements between two arrays;
  • Check if a object is completely empty;
  • Sorting an array by Brazillian date;
  • Change an array's item index to another;
  • Check if two objects are identical;
  • Reorder and array based on a key and value, moving items to the end of this array;
  • Reorder an specific item to the end of an array;
  • Get the last day of current year and month, returning the full date (YYYY-MM-DD);
  • Get the first day of current year and month, returning the full date (YYYY-MM-DD);
  • (PT-BR) Formata um dado CPF ou CNPJ em string plano (sem caracteres especiais) nas suas devidas máscaras;
  • (PT-BR) Formata um dado telefone em string plano (sem caracteres especiais) na sua devida máscara;
  • Get current date with the format DD/MM/YYYY;
  • Generate a random hexadecimal color;
  • "Title Case" a "snake_case" word;
  • Get a given percentage for a total number;
  • Check if a float number has a given precision;
/**
* Transforms texts in snake_case to "Title Case" with
* spaces separating.
* @param str - Word to be converted.
*/
const capitalizeSnakeCaseString = (str) => {
let res = str
.split("_")
.map(([firstChar,...rest]) => firstChar.toUpperCase() + rest.join("").toLowerCase())
.join(" ")
return res
}
/**
* Changes an array's index to another position.
*
* @param {Array} - Array to be modified;
* @param {Number} - element's current index;
* @param {Number}- element's desired index;
*/
const changeArrayIndex = (arr, fromIndex, toIndex) => {
const element = arr[fromIndex];
arr.splice(fromIndex, 1);
arr.splice(toIndex, 0, element);
}
// Tests
let arr = ['First', 'Second', 'Third', 'Fourth'];
changeArrayIndex(arr, 0, 3)
console.log(arr)
/**
* Checks if an object is identical, considerating the following:
*
* - Has same 'constructor';
* - Has same 'typeof';
* - Has same 'properties' and 'values' for them;
*/
const checkIfObjectIsIdentical = (object1, object2) => {
// Return 'false' if constructors aren't the same:
if (object1.constructor !== object2.constructor) {
return false
}
// Return if objects isn't instances of Object object:
if (!(object1 instanceof Object) && !(object2 instanceof Object)) {
return false
}
// Return 'false' if the typeof objects aren't the same:
if (typeof object1 !== 'object' && typeof object2 !== 'object') {
return false
}
// Checks if the object has same properties and values:
for (const key in object1) {
if (Object.prototype.hasOwnProperty.call(object1, key) && object1[key] === object2[key]) {
continue
} else {
return false
}
}
for (const key in object2) {
if (Object.prototype.hasOwnProperty.call(object2, key) && object2[key] === object1[key]) {
continue
} else {
return false
}
}
return true
}
// Testings ============================================
let obj1 = {a: 'item1', b: 'item2', c: 'item3'};
let obj2 = {a: 'item1', b: 'item2', c: 'item3'};
checkIfObjectIsIdentical(obj1, obj2);
/**
* Checks if a given float number has a given integer and float precision.
* @param value - Float number to be evaluated.
* @param precision.integers - Integers precision
* @param precision.floats - Floats precision
*/
const checkPrecision = (value, { integers = 1, floats = 2 }) => {
const splitted = value.toString().split('.')
const hasValidIntegers = splitted[0].length <= integers
const hasValidFloats = splitted[1].length <= floats
if (!hasValidIntegers || !hasValidFloats) { return false }
return true
}
checkPrecision(50.33, { integers: 2, floats: 2 })
/**
* Checks between two arrays the objects present in the first one that are missing in the second.
* @param {Array} param1 - Array 1
* @param {Array} param2 - Array 2
* @param {String} checkingProperty - Parameter name used as comparator.
**/
const getElementsMissing = (param1, param2, checkingProperty) => {
// find missing elements
let missingElements = param1.filter(e => !param2.find(a => e[checkingProperty] == a[checkingProperty]))
// mark 'em as missing
missingElements = missingElements.map(item => {
return { ...item, missing: true }
})
// join them
let arr2filled = param2.concat(missingElements)
// return it
return arr2filled
}
/**
* Formata uma string referente a um CPF ou CNPJ no formato ########### (cpf, sem caracteres especiais)
* ou ############## (cnpj, sem caracteres especiais) para o formato ###.###.###-## ou ##.###.###/####-##,
* respectivamente, baseado num tipo de pessoa provido como parametro..
* @param {String} str - Cpf ou CNPJ a ser formatado.
* @param {String} tipoPessoa Tipo de pessoa (F - física, J - jurídica)
*/
formataCpfCnpj (str, tipoPessoa) {
let result = ''
if (tipoPessoa === 'F') {
result = str.replace(/(\d{3})(\d{3})(\d{3})(\d{2})/, '$1.$2.$3-$4')
} else {
result = str.replace(/(\d{2})(\d{3})(\d{3})(\d{4})(\d{2})/g, '$1.$2.$3/$4-$5')
}
return result
}
/**
* Formata uma string referente a um telefone no formato ########### (celular com DDD + 9 dígitos)
* Ou ########## (telefone fixo com DDD + 8 digitos)
* @param {String} str - Número do telefone a ser formatado.
*/
formataNumeroTelefone (str) {
let result = ''
// Se menor que 11 é um número de tel. fixo
if (str && str.length < 11) {
result = str.replace(/(\d{2})(\d{4})(\d{4})/g, '($1) $2-$3')
} else {
result = str.replace(/(\d{2})(\d{5})(\d{4})/g, '($1) $2-$3')
}
console.log(result)
return result
}
/**
* Generates a random hexadecial color string. e.g.: "#2029d1"
*/
const generateRandomHexColor = () => `#${Math.floor(Math.random() * 16777215).toString(16)}`;
/**
* Just get the current date in the format DD/MM/YYYY.
*/
const getDateNow = () => {
const date = new Date();
const day = date.getDate() < 10 ? '0' + date.getDate() : date.getDate()
const month = (date.getMonth() + 1) < 10 ? ('0' + (date.getMonth() + 1)) : (date.getMonth() + 1)
const year = date.getFullYear()
return `${day}/${month}/${year}`
}
/**
* Returns the date of first day from current month and year as string in the format YYYY-MM-DD.
*/
const getMonthFirstDate = () => {
const yearNow = new Date().getFullYear()
let monthNow = new Date().getMonth() + 1
monthNow = monthNow < 10 ? '0' + monthNow : monthNow
const firstDay = '01'
return `${yearNow}-${monthNow}-${firstDay}`
}
/**
* Returns the date of last day from current month and year as string in the format YYYY-MM-DD.
*/
const getMonthLastDate = () => {
const yearNow = new Date().getFullYear()
let monthNow = new Date().getMonth() + 1
monthNow = monthNow < 10 ? '0' + monthNow : monthNow
const lastDay = new Date(yearNow, monthNow, 0).getDate()
return `${yearNow}-${monthNow}-${lastDay}`
}
/**
* Returns the percentage of a given percent
* relative to the total passed.
* @param {Number} percent - Percentage to get.
* @param {Number} total - Total number/percentage.
*/
const getPercentage = (percent, total) => {
const result = ((percent/ 100) * total).toFixed(2);
return result;
}
/*
* Checks if a object only have empty strings or null properties.
* @param {Object} - Object to be evaluated.
* @returns - true, if it's empty or false if it is not.
**/
const isObjEmpty = (obj) => {
return Object.keys(obj).every(x => {
return obj[x] === '' || obj[x] === null
})
}
/**
* Receives an array and a index for the item that will be pushed to the end of array.
* @param {Array} arr - Array to be reordered.
* @param {Number} elemIndex - index of the element to be pushed to end of array.
*/
const pushItemToEnd = (arr, elemIndex) => {
arr.push(arr.splice(elemIndex, 1)[0])
}
/**
* Sorts an array of dates (or an array of objects, modifying the a.split to a.MY_DATE_PARAM.split ) in the Brazillian format DD/MM/YYYY to ascending.
*
* @param {Array} datesArray - Array of dates.
*/
// TODO: Add params to get ascending or descending.
const sortArrayByBRDate = (datesArray) => {
datesArray.sort((a, b) => {
const aa = a.split('/').reverse().join()
const bb = b.split('/').reverse().join()
return aa < bb ? -1 : (aa > bb ? 1 : 0);
})
}
// tests
const dates = [
'30/01/2022',
'03/01/2020',
'25/01/2020',
'07/02/2020',
'27/01/2020',
'05/01/2020'
];
sortArrayByDate(dates);
console.log(dates);
/**
* Takes an array and reorder it based on a property and a vlaue to it passed as parameter.
* @param {Array} arr - Array to be modified;
* @param {String} prop - property to be considered in sorting;
* @param {*} propValue - prop value to be considered in sorting;
*/
const sortItemsToEnd = (arr, prop, propValue) => {
arr.sort((a, b) => {
return (a[prop]===propValue)-(b[prop]===propValue) || +(a[prop] > b[prop])||-(a[prop] < b[prop]);
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment