/*************************************************** * UTILS * Funções soltas de cunho geral que servem em outros locais do app * ****************************************************/ /************************************************************************* * * TYPES */ type ApplyVarsOptions = { start: string; end: string; }; /************************************************************************* * * COMPARAÇÃO DE VALORES */ /** * Verifica se um valor é vazio, null, array vazio ou objeto vazio. * Não considera 0 ou false como vazio. * * @example * * empty('') // -> true * empty(null) // -> true * empty(false) // -> false * empty(undefined) // -> true * * @param {*} value * @returns {Boolean} */ export declare const empty: (value: any) => boolean; /************************************************************************* * * VERIFICAÇÃO DE TIPOS */ /** * Verifica se o valor passado é do tipo array * * @example * * isArray([]) // -> true * isArray({}) // -> false * isArray(0) // -> false * isArray('claudio') // -> false * * @param {*} value * @returns {Boolean} */ export declare const isArray: (value: any) => boolean; /** * Verifica se o valor passado é do tipo objeto */ export declare const isObject: (value: any) => boolean; /** * Verifica se o valor passado é do tipo string * * */ export declare const isString: (value: any) => boolean; /** * Verifica se é um número inteiro. * * @examples * isInteger('1') // -> true * isInteger('1', true) // -> false * isInteger(1) // -> true * isInteger(1.2) // -> false * isInteger(1, true) // -> true * isInteger('1', true) // -> false * isInteger('claudio') // -> false * * @param {Any} value: Valor que será comparado * @param {Boolean} forceType: Define se deve verificar o tipo, e não apenas o número */ export declare const isInteger: (value: any, forceType?: boolean) => boolean; /** * Verifica se é no formato de float, independente do tipo * * @example * * isFloat('1') // -> true * isFloat(1, true) // -> true * isFloat('1', true) // -> false * isFloat(1) // -> true * isFloat(1.2) // -> true * isFloat('1.2') // -> true * isFloat('1.2', true) // -> false * isFloat('claudio') // -> false * isFloat(false) // -> false * * @param {*} value * @returns {Boolean} * */ export declare const isFloat: (value: any, forceType?: boolean) => boolean; /** * Verifica se é no formato de float, independente do tipo * * @example * * isNumeric('1') // -> true * isNumeric(1, true) // -> true * isNumeric('1', true) // -> false * isNumeric(1) // -> true * isNumeric(1.2) // -> true * isNumeric('1.2') // -> true * isNumeric('1.2', true) // -> false * isNumeric('claudio') // -> false * isNumeric(false) // -> false * * @param {*} value * @returns {Boolean} */ export declare const isNumeric: (value: any, forceType?: boolean) => boolean; /** * Verifica se um dado valor é um objeto JSON * * @example * * isJSON( true ) // -> false * isJSON( false ) // -> false * isJSON( '' ) // -> false * isJSON( null ) // -> false * isJSON( undefined ) // -> false * isJSON( NaN ) // -> false * isJSON( 'claudio' ) // -> false * isJSON( 4654 ) // -> false * isJSON( 0 ) // -> false * isJSON( [1,2,3] ) // -> false * isJSON( new Date() ) // -> false * isJSON( "{ age: 21 }" ) // -> false * isJSON( { age: 21 } ) // -> true * * * @param {*} value * @returns {Boolean} */ export declare const isJSON: (value: any) => boolean; /** * checkTypes * Verifica se o valor passado bate com algum dos tipos * http://tobyho.com/2011/01/28/checking-types-in-javascript/ * * checkTypes( 1, String ) // -> false * checkTypes( '1', String ) // -> true * checkTypes( 1, Number ) // -> true * checkTypes( '1', Number ) // -> false * checkTypes( 1, [String, Number] ) // -> true * checkTypes( 'a', [String, Number] ) // -> true * checkTypes( {}, [String, Number] ) // -> false * checkTypes( [], [String, Number] ) // -> false * checkTypes( [], [String, Number, Array] ) // -> true * checkTypes( {}, [String, Number, Array] ) // -> false * checkTypes( {}, [String, Number, Array, Object] ) // -> true * * @param {*} value * @param {*|[*]} types * @returns {Boolean} */ export declare const checkTypes: (value: any, types: any | any[]) => boolean; /************************************************************************* * * COMPARAÇÃO DE FORMATOS */ /** * Verifica se é um e-mail * * isEmail("claudio") // -> false * isEmail("claudio@claudio.com") // -> true * isEmail("") // -> false * isEmail(null) // -> false * isEmail(undefined) // -> false * isEmail([]) // -> false * isEmail({}) // -> false * isEmail(123) // -> false * */ export declare const isEmail: (value: any) => boolean; /** * Verifica se é uma data em um formato aceito pelo javascript * * @example * * isDate('12/12/29') // -> true * isDate('31/12/29') // -> false * isDate('12/31/29') // -> true * isDate('12/12/2029') // -> true * isDate('2029-12-12') // -> true * * @param {String|Number|Date} * @returns {Boolean} */ export declare const isDate: (value: string | number | Date) => boolean; /** * Verifica se é uma data válida em portugues * * @example * isDateBR('31/07/2020') // true * isDateBR('32/07/2020') // false * * * @param {String} * @returns {Boolean} */ export declare const isDateBR: (value: string) => boolean; /** * Verifica se uma hora informada possui o formato de hora: * 00:00 ou 00:00:00. * Por padrão na verifica os segundos. Passe seconds=true para * verificar também os segundos * * @example * * isTime('12:00') // -> true * isTime('23:00') // -> true * isTime('23:59') // -> true * isTime('24:00') // -> false * isTime('00:00') // -> true * isTime('-12:00') // -> false * isTime('aa:pp') // -> false * isTime('23:60') // -> false * isTime('00:00:00', true) // -> true * isTime('23:59:59', true) // -> true * isTime('24:59:59', true) // -> false * isTime('23:60:59', true) // -> false * isTime('23:59:65', true) // -> false * isTime('aa:bb:dd', true) // -> false * * * * @param {String} value * @param {Boolean} seconds * * */ export declare const isTime: (value: string, seconds?: boolean) => boolean; /** * Verifica se um valor é falsy, ou seja, mesmo convertido * para string a intenção dele deveria ser falso * * @example * * isFalsy(0) // -> true * isFalsy('') // -> true * isFalsy('0') // -> true * isFalsy(NaN) // -> true * isFalsy(null) // -> true * isFalsy('NaN') // -> true * isFalsy(false) // -> true * isFalsy('null') // -> true * isFalsy('false') // -> true * isFalsy(undefined) // -> true * isFalsy('undefined') // -> true * * @param {any} value */ export declare const isFalsy: (value: any) => boolean; /** * Verifica se um valor é falsy, ou seja, mesmo convertido * para string a intenção dele deveria ser falso * * @example * * isTruthy(0) // -> false * isTruthy('') // -> false * isTruthy('0') // -> false * isTruthy(NaN) // -> false * isTruthy(null) // -> false * isTruthy('NaN') // -> false * isTruthy(false) // -> false * isTruthy('null') // -> false * isTruthy('false') // -> false * isTruthy(undefined) // -> false * isTruthy('undefined') // -> false * * @param {any} value */ export declare const isTruthy: (value: any) => boolean; /************************************************************************* * * CONVERSÃO DE FORMATOS */ /******************** * BUSCA */ /** * Verifica 2 arrays e retorna os valores que estão em ambos * * @example * * intersect([1,2,3], [3,4,5]) // -> [ 3 ] * * @param {Array} array1 * @param {Array} array2 * @return {Array} Array contendo os valores que estão nos 2 arrays */ export declare const intersect: (array1: any[], array2: any[]) => any[]; /** * Retorna o valor de uma chave em um objeto de múltiplos níveis * * @example * let obj = { a:'1', b:{ c:10, d:2, e:{ f:'4', g:'5', h:{ i:'6' } } } } * objectPath( obj , 'b.e.h.i' ); // -> '6' * * @param {Object} obj * @param {String} path Endereço no formato 'chave.subchave.outrasubchave' * @returns {*} Valor de acordo com o caminho */ export declare function objectPath(obj: any, path: string): any; /******************** * FUNÇÕES DE APOIO */ /** * Agrupa um array de objetos por uma das chaves desse array. * * @todo Mesclar com o objectPath() acima e permitir agurpamentos multidimensionais * com * * @exemplo * const list = [ * {"id":1,"name":"claudio","age":37,"city":"fortaleza"}, * {"id":2,"name":"isa","age":9,"city":"natal"}, * {"id":3,"name":"jose","age":37,"city":"fortaleza"}, * {"id":4,"name":"marta","age":42,"city":"afonso bezerra"}, * {"id":5,"name":"joelma","age":42,"city":"afonso bezerra"}, * {"id":6,"name":"jose","age":24,"city":"assu"} * ] * * groupBy( list, 'name' ) * * { * "claudio":[ * {"id":1,"name":"claudio","age":37,"city":"fortaleza"} * ], * "isa":[ * {"id":2,"name":"isa","age":9,"city":"natal"} * ], * "jose":[ * {"id":3,"name":"jose","age":37,"city":"fortaleza"}, * {"id":6,"name":"jose","age":24,"city":"assu"} * ], * "marta":[ * {"id":4,"name":"marta","age":42,"city":"afonso bezerra"} * ], * "joelma":[ * {"id":5,"name":"joelma","age":42,"city":"afonso bezerra"} * ] * } * * * @param {Array} items Lista de objetos * @param {String} key Nome da chave que agrupará os demais dados */ export declare const groupBy: (items: object[], key: any) => any; /** * Gerador de chaves aleatórias * Pelo menos 1 dos parâmetros numbers, lower e upper precisa ser true. * Para que haja a máxima proteção contra conflitos, os três podem ser true * https://gist.github.com/6174/6062387#gistcomment-2742945 * * @example * * keyGenerator(5) // -> 11S9P * keyGenerator(5, false) // -> HrmTF * keyGenerator(5, false, false) // -> RHCWJ * keyGenerator(5, false, true, false) // -> vzuyn * * @param {Integer} length Tamanho gerado * @param {Boolean} numbers Define se existirão números * @param {Boolean} lower Define se existirão letras minúsculas * @param {Boolean} upper Define se existirão letras maiúsculas * @returns {String} */ export declare const keyGenerator: (length?: number, numbers?: boolean, lower?: boolean, upper?: boolean) => string; /** * Gerador de slug * Create SLUG from a string * This function rewrite the string prototype and also * replace latin and other special characters. * * @link * Forked by Gabriel Fróes - https://gist.github.com/gabrielfroes * Original Author: Mathew Byrne - https://gist.github.com/mathewbyrne/1280286 * * @example * * slug('José Cláudio + ') // -> 'jose-claudio * slug('José -- /\|<>Cláu=dio ') // -> 'jose-claudio * * @param {String} value * @returns {String} Valor convertido para slug */ export declare const slug: (value: string) => string; /** * Converte um número passado para o formato do Real Brasileiro * * https://stackoverflow.com/a/64909632/3240078 * NumberFormat use small non-breaking space (\u202f) for thousand separator * and normal non-breaking space beforece currency (\xa0) * * @example * currencyBR(12.34) // -> 'R$ 12,34' * currencyBR('12.34') // -> 'R$ 12,34' * currencyBR('12,34') // -> null * * @param {Number|String} value * @returns {String} */ export declare const currencyBR: (value: number | string) => string; /** * Converte um nome para as primeiras em maiúsculas, exceto as partes * que normalmente continuam em minúsculas, tipo "de", "dos" etc. * * @example * upperFirst('jose claudio medeiros de lima') // -> Jose Claudio Medeiros de Lima * upperFirst('JOSE CLAUDIO MEDEIROS DE LIMA') // -> Jose Claudio Medeiros de Lima * upperFirst('JoSe cLaUdIo MeDeIrOs De LiMa') // -> Jose Claudio Medeiros de Lima * * @param {String} value * @returns {String} * */ export declare const upperFirst: (value: string) => string; /** * Reescreve um objeto aplicando um prefixo definido às suas chaves * * @example * const original = { * name: 'ze', * age: 23 * } * * prefixObjectKeys( original, 'people.*.' ) * // -> * { * 'people.*.name': 'ze', * 'people.*.age': 23, * } * * * @param {Object} obj Objecto original * @param {String} prefix Prefixo que será aplicado */ export declare function prefixObjectKeys(obj: any, prefix?: string): any; /** * objectFlat() * Recebe um objeto e o transforma em uma versão plana, com suas chaves * multinível unidas por um ponto. * * @link https://stackoverflow.com/a/34514143/3240078 * * @example * * const obj = { * name: 'claudio' * address: { street': 'Monkey St.' } * } * * objectFlat( obj ) * // -> { name: 'claudio', 'address.street': 'Monkey St.' } * * objectFlat( obj, '_' ) * // -> { name: 'claudio', address_street: 'Monkey St.' } * * objectFlat( {name:'ze', info:{age:null}}, '_' ) * // -> { name: 'claudio', address_street: 'Monkey St.' } * * objectFlat( {name:'ze', info:{age:null}}, '_' ) * // -> { name: 'ze', info_age: null } * * objectFlat( {name:'ze', info:{age:null}}, '_' ) * // -> { name: 'ze', info_age: null } * * objectFlat({ birth: new Date('1982-07-31'), address: { number: null, } }, '_') * // -> { birth: new Date('1982-07-31'), address_number: null } * * @param {Object} obj * @param {String} separator Default "." * @returns {Object} */ export declare function objectFlat(obj: Record, separator?: string): Record; /** * Mantém somente as chaves do objeto que estão na lista branca * * @example * * * const address = { * id: 1, * description: 'decrição', * city_id: 123, * city: { * id: 123, * name: 'açu' * } * } * * whiteList(address, ['id', 'description', 'city_id']) * // -> { id: 1, description: 'decrição', city_id: 123 } * * whiteList([address, address], ['id', 'description']) * // -> [ * { id: 1, description: 'decrição' }, * { id: 1, description: 'decrição' } * ] * * @param {Object|Array} obj Objeto inicial. Se for array, aplica um loop aos elementos * @param {Array} keys Lista de chaves permitidas */ export declare const whiteList: (obj: any | any[], keys: any[]) => any; /** * Substitui os caracteres acentuados por semelhantes não acentuados respeitando * maiúsculas e minúsculas * * @example * removeAccent('Açu') // -> Acu * * @param value * @returns */ export declare const removeAccent: (value: string) => string; /** * randomNumber() * Cria um número aleatório com o número de caracteres * * @example * randomNumber(8, true) // -> 00083159 * randomNumber(4) // -> 831 * * @param {Integer} length * @param {Boolean} forceLength Adiciona zeros à esquerda para ter os números de caractes exatos * @returns {String} */ export declare function randomNumber(length: number, forceLength?: boolean): number | string; /** * Limpa um número informado, retirando caracteres diferentes de números, * preenchendo com zeros à esquerda se for menor que o tamanho exato e * removendo uma parte do número se for maior que tamanho definido. * * 1) Retira caracteres não-numéricos * 2) Preenche com zeros à esquerda se 'value' for menor que 'length' * 3) Remove caracteres à direita se 'value' for maior que 'length' * * @example * clearNumber(12345-6, 6) // -> 123456 * clearNumber(12345678, 3) // -> 123 * clearNumber(12345, 10) // -> 0000001234 * * @param {Number|String} value * @param {Number} length Tamanho exato. Se for null, só retira os caracteres não-numéricos * @returns {String} Número com o tamanho exato */ export declare function clearNumber(value: string | number, length?: number | null): string; /** * Limpa os valores falsy do objeto informado * * @example * clearFalsy({ id:1, age:'0', idade: 'NaN', birth: '' }); // -> { id: 1 } * * @param {Object} value * @returns {Object} Objeto sem os valores */ export declare function clearFalsy(value: Record): Record; /** * insertAtPosition() * Insere um conjunto de caracteres em um local específico de uma string * * @example * insertAtPosition('AAABBB', 'C', 3) // -> AAACBBB * insertAtPosition('000011122223445555', 99, 7) // -> 00001119922223445555 * * @param {String} value Valor original * @param {String|Number} insertValue Valor que será inserido * @param {Number} position Posição que receberá o novo valor * @returns {String} * */ export declare function insertAtPosition(value: string, insertValue: string | number, position: number): string; /** * removeFromPosition() * Retira um conjunto de caracteres de um local específico de uma string * * @example * removeFromPosition('00001119922223445555', 7,9) // -> 000011122223445555 * removeFromPosition('AAACBBB', 3,4) // -> AAABBB * * @param {String|Number} value Valor original * @param {String|Number} startPosition * @param {String|Number} endPosition * @returns {String} * */ export declare function removeFromPosition(value: string, startPosition: number, endPosition: number): string; /** * applyVars() * Aplica variáveis a um texto * * @example * const values = { id: 1, name: 'claudio', age: 39, email: 'email@mail.com' } * * applyVars('Olá, :name. Seu e-mail ainda é :email?', values) * applyVars('Olá, {name}. Seu e-mail ainda é {email}?', values, { start: '{', end: '}' }) * applyVars('Olá, {{name}}. Seu e-mail ainda é {{email}}?', values, { start: '{{', end: '}}'}) * * @param {String} text * @param {Object} vars * @param {ApplyVarsOptions} options */ export declare function applyVars(value: string, vars: Record, options?: Partial): string; /** * Remove specialChars */ export declare function removeSpecialChars(value: string): string; /** * applyMask() * Aplica uma máscara a uma string * * @example * applyMask('59650000', '00.000-000') // -> 59.650-000 * applyMask('99877665544', '(00) 0 0000-0000') // -> (99) 8 7766-5544 * * @param {String|Number} value Valor original * @param {String} mask * @returns {String} * */ export declare function applyMask(value: string | number, mask: string): string; /** * randomLetter() * Pega uma letra maiúscula aleatoriamente * * @example * randomLetter() // -> A * randomLetter() // -> S * * @returns {String} */ export declare function randomLetter(): string; /** * Exibe uma quantidade como string numérica * * @example * quantity(0, 'mensagens', 'mensagem', 'nenhuma mensagem') // nenhuma mensagem * quantity(0, 'mensagens', 'mensagem', null) // 0 mensagem * quantity(1, 'mensagens', 'mensagem', 'nenhuma mensagem') // 1 mensagem * quantity(2, 'mensagens', 'mensagem', 'nenhuma mensagem') // 2 mensagens * * @param {Number|'String} A quantidade * @param {String} Sufixo que será usado quando a quantidade for mais de um * @param {String} Sufixo que será usado quando a quantidade for 1 * @param {String|Null} Texto usado quando a quantidade for zero. Se estiver em branco, * será usado o sufixo individual * * @return {String} Texto contendo as variações */ export declare const quantity: (qty: number | string, suffixMany: string, suffixOne: string, textEmpty: string | null) => string; /** * Converte bytes em um de seus múltiplos. * * @example * filesize(null) // -> 0 Kb * filesize('') // -> 0 Kb * filesize(12354353) // -> 11 mb * * @param {Number} bytes * @return {String} Valor convertido para kb, mb etc */ export declare const filesize: (bytes: number | string) => string; /** * Ordena um array de objetos a partir de uma chave * * sortByKey( [{name: 'marta'}, {name: 'claudio'}, {name: 'isa'}], 'name' ) * // -> [ {name: 'claudio',}, {name: 'isa',}, {name: 'marta',} ] * * @param {Object[]} list */ export declare const sortByKey: (list: Array>, key: any) => Record[]; /** * * Converte um valor boolean, analisando seu conteúdo, mesmo que seja uma string. * Se for um valor possivelmente falsy, converte para falsy * * @example * toBoolean("a"); // -> true * toBoolean(1); // -> true * toBoolean("true"); // -> true * toBoolean("0"); // -> false * toBoolean(0); // -> false * toBoolean("false"); // -> false * toBoolean(false); // -> false * toBoolean(""); // -> false * toBoolean("undefined"); // -> false * toBoolean(undefined); // -> false * toBoolean("NaN"); // -> false * toBoolean(NaN); // -> false * toBoolean("null"); // -> false * toBoolean(null); // -> false * * @param {*} value * @returns {Boolean} */ export declare function toBoolean(value: any): boolean; /** * * Gera um UUID V4 ordenável, usando a data atual como base * */ export declare function timeUUID(): string; export {}; //# sourceMappingURL=main.d.ts.map