iohpjsfunctions
v1.6.1
Published
//string functions function capital(str) { if (!str) return '';
Downloads
8
Readme
//string functions function capital(str) { if (!str) return '';
//str.replace(/\b\w(?!\b)/g, s => s.toUpperCase());
return (str+"").replace(/([áéíóúÁÉÍÚÓñÑ]|\w)*\s*/g, function(txt){
return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();
});
}
function capitalTitulo(s) { var preposiciones = [ 'a','al','ante','bajo','cabe','con','contra','de','del','desde','durante', 'en','entre','hacia','hasta','mediante','para','por','según','sin', 'so','sobre','tras','versus','via','vs','las','los','y','x','o','ó' ]; s=capital(s); var r='\s+('+preposiciones.join("|")+')\s+'; var reg=new RegExp(r, "ig");
s = s.replace(reg, function(match) {
return match.toLowerCase();
});
s=s.replace(/cxc/gi,'CxC');
s=s.replace(/cxp/gi,'CxP');
s=s.replace(/srl/gi,'SRL');
s=s.replace(/llc/gi,'LLC');
s=s.replace(/ars/gi,'ARS');
return s;
}
function sentenceCase(str){ str = (str+"").toLowerCase(); return str.replace(/^[a-z]|(?<=(.))\s*[a-z]|(?<=(?))\s*[a-z]|(?<=(!))\s*[a-z]/gi, function (letter) { return letter.toUpperCase(); }).trim();
}
function strTruncate(str,length,concat = ''){ return (str+"").substring(0,(length??str.length)) + concat; }
function getRandomInt() { return new Date().getTime() }
//array and objects functions function isEmptyObject(obj) { for(var prop in obj) { if (Object.prototype.hasOwnProperty.call(obj, prop)) { return false; } } return true; } function jsonCopy(src) { if(!src) return null; return JSON.parse(JSON.stringify(src)); } // TODO verificar una de las dos funciones empty object function isObjEmpty(obj) { for(var key in obj) { if(obj.hasOwnProperty(key)) return false; } return true; }
function sortBy(arr, prop) { return arr.sort((a, b) => (a[prop] > b[prop]) ? 1:-1);
//(a.color > b.color) ? 1 : -1
}
// TODO buscar la manera de usar array filter function arraySearch(myArray,nameKey,value){ var a = []; myArray = jsonCopy(myArray); for (var i=0; i < myArray.length; i++) { var arrObj = myArray[i]; for(var o in arrObj){ var find = 0; if(typeof value !='undefined'){ var key = nameKey.split(","); for(var b=0; b < key.length; b++){ if(o.toUpperCase() == key[b].toUpperCase()){ var res = (arrObj[o]+"").toUpperCase().search(value.toUpperCase()); if(res >= 0){ //var regEx = new RegExp(value, "ig"); //arrObj[o] = arrObj[o].replace(regEx,value); a.push(arrObj); find = 1; break; } } } }else{ var res = (arrObj[o]+"").toUpperCase().search(nameKey.toUpperCase()); if(res >= 0){ //var regEx = new RegExp(nameKey, "ig"); //arrObj[o] = arrObj[o].replace(regEx,nameKey); a.push(arrObj); find = 1; break; } } if(find) break; } } return a; } // TODO verificar el uso de esta funcion arr2obj function arr2obj(arr){ var obj = {}; for(var i in arr){ obj[i] = arr[i]; } return obj; } // TODO verificar el uso de esta funcion objKeys2Lower function objKeys2Lower(obj){ var key, keys = Object.keys(obj); var n = keys.length; var newobj={} while (n--) { key = keys[n]; newobj[key.toLowerCase()] = obj[key]; } return newobj; }
//number function function isNumeric(val){ var regEx = new RegExp('^[0-9]*$','g'); if(regEx.exec(val)) return true; return false; } // TODO verificar el uso de esta funcion objKeys2Lower function num_format2(num){ // Create our number formatter. var formatter = new Intl.NumberFormat('en-US'); var res = formatter.format(num); return res; }
function num_format(omoney, decimals, prefix, thousandSeparator = true){ var num = omoney; var mygrid = this; var aux = 0; var float; var money; var dec;
var dcm = '';
var res;
var d = '';
var prx;
if(typeof num === 'null') num = 0;
num = num+"";
if(decimals) num = parseFloat(num).toFixed(decimals);
float = num.split(".");
money = ''+float[0];
dec = ''+float[1];
res = num;
switch(typeof prefix){
case 'string':
prx = prefix;
break;
}
thousandSeparator = (typeof thousandSeparator !== "undefined") ? thousandSeparator : ",";
if (thousandSeparator) money=money.replace(/(\d)(?=(\d{3})+(?!\d))/g, '$1,');
res = money+(typeof dec != 'undefined' && dec != 'undefined'? ("."+dec):"");
if(prx && typeof prx !== 'undefined') return res = prx+' '+res;
return res;
}
//https://developer.mozilla.org/es/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString
// TODO mejorar esta vaina formaDate
//date functions
function formaDate(dt,withhours = true){
if(dt) var d = new Date(dt);
else var d = new Date();
var dd = String(d.getDate()).padStart(2, '0');
var mm = String(d.getMonth() + 1).padStart(2, '0'); //January is 0!
var yyyy = d.getFullYear();
var strTime = "";
if(withhours){
var hours = d.getHours();
var minutes = d.getMinutes();
var ampm = hours >= 12 ? ' p.m.' : ' a.m.';
hours = hours % 12;
hours = hours ? hours : 12;
minutes = minutes < 10 ? '0'+minutes : minutes;
strTime = ${hours}:${minutes} ${ampm}
;
}
dt = dd + '/' + mm + '/' + yyyy + strTime;
return dt;
}
// date
is a Date
object
function formatYmd(date){
//console.log(date);
return date.toISOString().slice(0, 10)
};
// Example
//formatYmd(new Date()); // 2020-05-06
// TODO poner estas funciones en un archivo dentro de la carpeta del componente que los llama async function blobToBase64(blob) { return new Promise((resolve, _) => { const reader = new FileReader(); reader.onloadend = () => resolve(reader.result); reader.readAsDataURL(blob); }); }
async function pasteImage(evt) { // Get the data of clipboard const clipboardItems = evt.clipboardData.items; const items = [].slice.call(clipboardItems).filter(function (item) { // Filter the image items only return item.type.indexOf('image') !== -1; }); if (items.length === 0) { return; }
const item = items[0];
// Get the blob of image
const blob = item.getAsFile();
// Assume that we have an `img` element
// <img id="preview" />
var base64 = await blobToBase64(blob);
return {base64:base64,blob:blob};
}
function b64toBlob(b64Data, contentType='', sliceSize=512){ const byteCharacters = atob(b64Data); const byteArrays = [];
for (let offset = 0; offset < byteCharacters.length; offset += sliceSize) {
const slice = byteCharacters.slice(offset, offset + sliceSize);
const byteNumbers = new Array(slice.length);
for (let i = 0; i < slice.length; i++) {
byteNumbers[i] = slice.charCodeAt(i);
}
const byteArray = new Uint8Array(byteNumbers);
byteArrays.push(byteArray);
}
const blob = new Blob(byteArrays, {type: contentType});
return blob;
}
function downloadcsv(items,name="Exportado a CSV"){ let csv // Loop the array of objects for(let row = 0; row < items.length; row++){ let keysAmount = Object.keys(items[row]).length let keysCounter = 0
// If this is the first row, generate the headings
if(row === 0){
// Loop each property of the object
for(let key in items[row]){
// This is to not add a comma at the last cell
// The '\r\n' adds a new line
csv += key + (keysCounter+1 < keysAmount ? ';' : '\r\n' );
keysCounter++;
}
}else{
for(let key in items[row]){
csv += items[row][key] + (keysCounter+1 < keysAmount ? ';' : '\r\n' );
keysCounter++;
}
}
keysCounter = 0
}
// Once we are done looping, download the .csv by creating a link
let link = document.createElement('a')
link.id = 'download-csv'
link.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(csv));
link.setAttribute('download', name+'.csv');
document.body.appendChild(link);
document.querySelector('#download-csv').click();
link.remove();
}
var tableToExcel = (function() { var uri = 'data:application/vnd.ms-excel;base64,' , template = 'Reporte Exportado{table}' , base64 = function(s) { return window.btoa(unescape(encodeURIComponent(s))) } , format = function(s, c) { return s.replace(/{(\w+)}/g, function(m, p) { return c[p]; }) } return function(name, title = "", data=[]) { /let elementList = document.querySelectorAll(".d-none"); for (let i = 0; i < elementList.length; i++) { elementList[i].classList.add("d-show"); } if (!table.nodeType) table = document.getElementById(table)/
var c, r, t,table = document.createElement('table');
let cols = [];
if(data?.length) cols = Object.keys(data[0]);
t=table;
r = t.insertRow(0);
for (let o = 0; o < cols.length; o++) {
const col = cols[o];
c = r.insertCell(o);
c.innerHTML = col;
}
for (let i = 0; i < data.length; i++) {
const element = data[i];
r = t.insertRow(i+1);
for (let o = 0; o < cols.length; o++) {
const col = cols[o];
c = r.insertCell(o);
c.innerHTML = data[i][col];
}
}
//document.getElementById("addtable").appendChild(t);
table = t;
var ctx = {worksheet: name || 'Worksheet', table: table.innerHTML}
var element = document.createElement('a');
element.setAttribute('href', uri + base64(format(template, ctx)));
let today = new Date();
title += "-"+today.getFullYear()+""+(today.getMonth()+1)+""+today.getDate()+"-"+today.getHours() +""+ today.getMinutes() +""+ today.getSeconds()+".xlsx";
element.setAttribute('download', title);
element.style.display = 'none';
document.body.appendChild(element);
element.click();
document.body.removeChild(element);
//window.location.href = uri "+ base64(format(template, ctx))
/*for (let i = 0; i < elementList.length; i++) {
elementList[i].classList.remove("d-show");
}*/
}
})();