Gathering detailed insights and metrics for @gilbarbara/helpers
Gathering detailed insights and metrics for @gilbarbara/helpers
npm install @gilbarbara/helpers
Typescript
Module System
Node Version
NPM Version
98.5
Supply Chain
99.2
Quality
84.1
Maintenance
100
Vulnerability
99.6
License
TypeScript (100%)
Total Downloads
4,120,398
Last Day
7,016
Last Week
36,735
Last Month
122,727
Last Year
3,342,582
12 Stars
164 Commits
1 Forks
5 Watching
1 Branches
1 Contributors
Latest Version
0.9.5
Package Id
@gilbarbara/helpers@0.9.5
Unpacked Size
288.22 kB
Size
83.30 kB
File Count
23
NPM Version
10.8.2
Node Version
20.18.1
Publised On
06 Jan 2025
Cumulative downloads
Total Downloads
Last day
-6.1%
7,016
Compared to previous day
Last week
1.6%
36,735
Compared to previous week
Last month
-22%
122,727
Compared to previous month
Last year
336.7%
3,342,582
Compared to previous year
2
Collection of useful functions
1npm i @gilbarbara/helpers
1import { unique } from '@gilbarbara/helpers'; 2 3const password = unique(24, { includeSymbols: true }); 4console.log(password); // g9HBfQeeOgrP.V1?JhETxn9P
createArray(size: number, start: number = 1): number[]
Create a sequential array of numbers.
getRandomItem<T>(input: T[]): T
Get a random item from an array.
quickSort<T extends string | number>(input: T[]): T[]
Sort an array of numbers using a quick sort algorithm.
shuffle<T = unknown>(input: T[]): T[]
Shuffle an array using the Fisher-Yates algorithm.
sortByLocaleCompare(key?: string, options?: Intl.CollatorOptions & { descending?: boolean }): SortFunction
Returns a sort function with localeCompare comparison.
1interface SortFunction<T = string> { 2 (left: PlainObject, right: PlainObject): number; 3 (left: T, right: T): number; 4}
1// with an array of strings 2const strings = ['Mãe', 'limão', 'cachê', 'tião', 'amô', 'côncavo']; 3strings.sort(sortByLocaleCompare()); 4// [ 'amô', 'cachê', 'côncavo', 'limão', 'Mãe', 'tião' ] 5 6// with an array of objects 7const objects = [{ key: 'réservé' }, { key: 'Premier' }, { key: 'Cliché' }, { key: 'communiqué' }, { key: 'café' }, { key: 'Adieu' }]; 8objects.sort(sortByLocaleCompare('key', { descending: true })); 9/* 10[ 11{ key: 'réservé' }, 12{ key: 'Premier' }, 13{ key: 'communiqué' }, 14{ key: 'Cliché' }, 15{ key: 'café' }, 16{ key: 'Adieu' } 17] 18*/
sortByPrimitive<T extends number | boolean>(key?: string, descending?: boolean = false): SortFunction
Returns a sort function with primitive values comparison.
1interface SortFunction<T = string> { 2 (left: PlainObject, right: PlainObject): number; 3 (left: T, right: T): number; 4}
1const objects = [{ cycle: 3, status: true }, { cycle: 1, status: false }, { cycle: 3, status: true }, { cycle: 4, status: false }]; 2objects.sort(sortByPrimitive('status', true)); 3/* 4[ 5{ cycle: 3, status: true }, 6{ cycle: 3, status: true }, 7{ cycle: 1, status: false }, 8{ cycle: 4, status: false } 9] 10*/
sortComparator(left: string | number, right: string | number): number
Basic sort comparator.
splitIntoChunks<T>(array: T[], chunkSize: number = 25): T[][]
Split an array into chunks.
ASYNC_STATUS
A constant with possible async statuses.
cors(data: any, statusCodeOrOptions: number | CorsOptions = 200): CorsResponse
Returns a CORS response.
1type HttpMethods = 'GET' | 'POST' | 'PATCH' | 'PUT' | 'DELETE'; 2 3interface CorsOptions { 4 /** @default true */ 5 allowCredentials?: boolean; 6 /** @default [] */ 7 allowedHeaders?: string[]; 8 /** @default ['GET'] */ 9 methods?: HttpMethods[]; 10 /** @default * */ 11 origin?: string; 12 responseHeaders?: Record<string, string>; 13 /** @default 200 */ 14 statusCode?: number; 15} 16 17interface CorsResponse { 18 body: string; 19 headers: Record<string, string>; 20 statusCode: number; 21}
poll(condition: () => boolean, options?: PollOptions): Promise<void>
Awaits for the condition to be true based on the options.
1interface PollOptions { 2 delay?: number; // 1 (seconds) 3 maxRetries?: number; // 5 (seconds) 4}
request<D = any>(url: string, options?: RequestOptions): Promise<D>
Perform an async request.
1type HttpMethods = 'GET' | 'POST' | 'PATCH' | 'PUT' | 'DELETE'; 2 3interface RequestOptions { 4 body?: any; 5 headers?: PlainObject; 6 method?: HttpMethods; 7}
You will need a polyfill if your Node version does not support fetch.
sleep(seconds?: number = 1): Promise<void>
Block async execution for X seconds.
isIsoDate(input?: string): boolean
Check if the input is an ISO date.
isoDate(input?: string | number): string
Returns an ISO date.
isValidDate(input: string | number | Date): boolean
Check if the input is a valid date.
now(): number
Returns a unix timestamp (seconds since 1970-01-01 00:00 UTC).
timeSince(input: Date | string | number, options?: TimeSinceOptions): string
Returns how much time has passed since the input date.
You can change the locale with the options.
If the plural form just adds an
s
to the end, you don't need to pass it. It will add it automatically.
1interface TimeSinceOptions { 2 day?: string; // day 3 days?: string; 4 hour?: string; // hour 5 hours?: string; 6 minute?: string; // minute 7 minutes?: string; 8 month?: string; // month 9 months?: string; 10 prefix?: string; 11 second?: string; // second 12 seconds?: string; 13 skipWeeks?: boolean; // true 14 suffix?: string; // ago 15 week?: string; // week 16 weeks?: string; 17 year?: string; // year 18 years?: string; 19}
1timeSince(twoDaysAgo) // 2 days ago 2timeSince(twoWeeksAgo, { skipWeeks: true }) // 14 days ago 3timeSince(twoDaysAgo, { day: 'Tag', days: 'Tage', prefix: 'Vor', suffix:'' }) // Vor 2 Tage 4timeSince(twoWeeeksAgo, { suffix: 'atrás', week: 'semana' }) // 2 semanas atrás
timestamp(input?: Date | string): number
Get the timestamp for a date.
isDarkMode(): boolean
Detect if the device is in dark mode.
isTouchDevice(): boolean
Detect if the device supports touch events.
prefersReducedMotion(): boolean
Detect if the user prefers reduced motion.
formatBoolean(input: boolean): 'Yes' | 'No'
Format the boolean into Yes / No.
formatCPF(input: string): string
Format the string into a CPF.
formatDateLocale(input: string, options?: FormatDateLocaleOptions): string
Format the ISO date string using locale.
1interface FormatDateLocaleOptions { 2 locale?: string; // > 'en-GB' 3 showTime?: boolean; // > false 4}
formatMoney(input: number, options?: FormatMoneyOptions): string
Format the number into a money string.
1interface FormatMoneyOptions { 2 decimalChar?: ',' | '.'; // > '.' 3 showCents?: boolean; // > false 4 symbol?: string; // > '$' 5 thousandsChar?: ',' | '.'; // > ',' 6}
formatPhoneBR(input: string): string
Format the string into a brazilian phone.
formatPhoneUS(input: string): string
Format the string into a US phone.
formatPostalCodeBR(value: string): string
Format the string into a brazilian zip code.
debounce(callback: (...parameters: any[]) => void, delay: number): Function
Creates a debounced version of a callback function.
demethodize(fn: Function): Function
Decouple the method from the prototype.
measureExecutionTime<T = any>(callback: Function): Promise<T>
Measure function execution time.
noop(): void
An empty function that does nothing.
once<T extends (...arguments_: Array<any>) => any>(fn: T): T
Creates a function that will only be called once.
Repeat calls return the value of the first invocation.
pipe<T>(...functions: Array<(argument: T) => T>)
Combine multiple functions into one.
The output of each function is passed as the input to the next.
conditional<TReturn>(cases: Array<Case<TReturn>>, defaultCase?: () => TReturn): TReturn | undefined
A replacement for switch statements with dynamic expressions cases.
1type Case<T = void> = [boolean, () => T];
1let type: string = ''; 2 3conditional( 4[ 5 [type === 'a', () => console.log('a')], 6 [[type].includes('b'), () => console.log('b')], 7 [type === 'c', () => console.log('c')], 8], 9() => console.log('default'), 10);
copyToClipboard(input: string): Promise<boolean>
Copy the string to the clipboard.
1const toLocaleString = demethodize(Number.prototype.toLocaleString); 2const numbers = [2209.6, 124.56, 1048576]; 3 4numbers.map(toLocaleString); // ['2,209.6', '124.56', '1,048,576']
getDataType(input: unknown, toLowerCase = false): string
Get the data type of variable.
1getDataType([1, 2, 3]); // Array 2getDataType(/\d+/); // RegExp 3getDataType(() => {}, true) // function
invariant(condition: any, message: string): asserts condition
Check if the value is truthy. Otherwise, it will throw.
isJSON(input: string): boolean
Check if a string is a valid JSON.
isRequired(input?: string = 'parameter', type: Constructable = TypeError): void
Throws an error of the Constructable type.
1function exec(input: string = isRequired('input')) {} 2exec() // Throws an TypeError with '"input" is required' 3 4function evaluate(input: string = isRequired('input', SyntaxError)) {} 5exec() // Throws an SyntaxError with '"input" is required'
logger(type: string, title: string, data: any, options?: LoggerOptions): void
Log grouped messages to the console.
1interface LoggerOptions { 2 collapsed?: boolean; // true 3 hideTimestamp?: boolean; // false 4 skip?: boolean; // false 5 typeColor?: string; // 'gray' 6}
on<T extends Window | Document | HTMLElement | EventTarget>(
target: T | null,
...rest: Parameters<T['addEventListener']> | [string, Function | null, ...any]
): void
Add the event listener to the target
off<T extends Window | Document | HTMLElement | EventTarget>(
target: T | null,
...rest: Parameters<T['removeEventListener']> | [string, Function | null, ...any]
): void
Remove the event listener from the target
nullify<T>(value: T): T | null
Returns the value or null.
popupCenter(url: string, title: string, width: number, height: number): Window | null
Open a centered popup window and returns it.
px(value: string | number | undefined): string | undefined
Convert a number or numeric value to px.
Otherwise, return the value.
unique(length?: number = 8, options?: UniqueOptions): string
Returns a random string.
1interface UniqueOptions { 2 includeLowercase?: boolean; // true 3 includeNumbers?: boolean; // true 4 includeSymbols?: boolean; // false 5 includeUppercase?: boolean; // true 6}
uuid(): string
Returns a UUID v4 string.
ceil(input: number, digits?: number = 2): number
Ceil decimal numbers.
clamp(value: number, min?: number = 0, max?: number = 100): number
Limit the number between ranges.
floor(input: number, digits?: number = 2): number
Floor decimal numbers.
pad(input: number, digits?: number = 2): string
Pad a number with zeros.
percentage(input: number, total: number, digits?: number = 2): number
Calculate the percentage of a number in relation to the total.
randomInt(min?: number = 0, max?: number = 10): number
Returns a random integer.
round(input: number, digits?: number = 2): number
Round decimal numbers.
cleanUpObject(input: PlainObject): PlainObject
Remove properties with undefined values from an object.
getNestedProperty(input: PlainObject | any[], path: string): any
Get a nested property inside an object or array.
1getNestedProperty({ children: { letters: ['a', 'b', 'c'] } }, 'children.letters'); 2// returns ['a', 'b', 'c'] 3getNestedProperty({ children: { letters: ['a', 'b', 'c'] } }, 'children.letters.1'); 4// returns 'b' 5getNestedProperty([{ a: 5 }, { a: 7 }, { a: 10 }], '0.a'); 6// returns 5
You may also use a wildcard (+) to get multiple array values:
1getNestedProperty([{ a: 5 }, { a: 7 }, { a: 10 }], '+.a'); 2// returns [5, 7, 10] 3getNestedProperty({ children: [{ a: 5 }, { a: 7 }, { a: 10 }] }, 'children.+.a'); 4// returns [5, 7, 10]
invertKeys(input: PlainObject): PlainObject
Invert object key and value.
keyMirror(input: PlainObject): PlainObject
Set the key as the value.
mergeProps<TDefaultProps, TProps>(defaultProps: TDefaultProps, props: TProps): TProps
Merges the defaultProps with literal values with the incoming props, removing undefined values from it that would override the defaultProps.
The result is a type-safe object with the defaultProps as required properties.
objectEntries<T extends PlainObject<any>>(input: T): Array<{ [K in keyof T]-?: [K, T[K]] }[keyof T]>
Type-safe Object.entries().
objectKeys<T extends PlainObject<any>(input: T): Array<keyof T>
Type-safe Object.keys().
objectToArray(input: PlainObject, includeOnly?: string): Array<PlainObject>
Convert an object to an array of objects.
omit<T extends PlainObject, K extends keyof T>(input: T, ...filter: K[]): PlainObject
Remove properties from an object.
pick<T extends PlainObject, K extends keyof T>(input: T, ...filter: K[]): PlainObject
Select properties from an object.
queryStringFormat(input: PlainObject, options?: QueryStringFormatOptions): string
Stringify a shallow object into a query string.
1interface QueryStringFormatOptions { 2 addPrefix?: boolean; 3 encodeValuesOnly?: boolean; 4 encoder?: (uri: string) => string; 5}
queryStringParse(input: string): PlainObject
Parse a query string.
sortObjectKeys(input: PlainObject): PlainObject
Sort object keys.
mean(input: number[], precision?: number): number
Returns the average of two or more numbers.
median(input: number[]): number
Returns the median of two or more numbers.
mode(input: number[]): number
Returns the mode of two or more numbers.
capitalize(input: string): string
Capitalize the first letter.
cleanupHTML(input: string): string
Clean up HTML content.
cleanupNumericString(input: string): string
Clean up a numeric string.
cleanupURI(input: string): string
Clean up URI characters.
getInitials(input: string): string
Get initials from the name.
pluralize(singular: string, plural: string | undefined, quantity: number): string
Returns the singular or plural based on the quantity.
If the plural form just adds an
s
to the end, you don't need to pass it. It will add it automatically.
removeAccents(input: string): string
Remove accents.
removeEmojis(input: string): string
Remove emojis.
removeEmptyTags(input: string): string
Remove empty HTML Tags (including whitespace).
removeNonPrintableCharacters(input: string): string
Remove non-printable ASCII characters.
removeTags(input: string): string
Remove HTML tags.
removeWhitespace(input: string): string
Remove whitespace.
slugify(input: string): string
Format the string into a slug.
isValidCPF(value: string): boolean
Check if the CPF is valid.
isValidEmail(value: string): boolean
Check if the email is valid.
@throws
validatePassword(password: string, options?: ValidatePasswordOptions): boolean
Validate password length and required characters.
1interface ValidatePasswordOptions { 2 maxLength?: string; 3 maxLengthMessage?: string; 4 minLength?: string; 5 minLengthMessage?: string; 6 regex?: RegExp; 7 requiredCharactersMessage?: string; 8}
MIT
No vulnerabilities found.
Reason
no dangerous workflow patterns detected
Reason
no binaries found in the repo
Reason
license file detected
Details
Reason
packaging workflow detected
Details
Reason
4 commit(s) and 0 issue activity found in the last 90 days -- score normalized to 3
Reason
SAST tool is not run on all commits -- score normalized to 1
Details
Reason
9 existing vulnerabilities detected
Details
Reason
Found 0/20 approved changesets -- score normalized to 0
Reason
detected GitHub workflow tokens with excessive permissions
Details
Reason
dependency not pinned by hash detected -- score normalized to 0
Details
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
security policy file not detected
Details
Reason
project is not fuzzed
Details
Score
Last Scanned on 2025-01-13
The Open Source Security Foundation is a cross-industry collaboration to improve the security of open source software (OSS). The Scorecard provides security health metrics for open source projects.
Learn More