Installations
npm install @gilbarbara/helpers
Developer Guide
Typescript
Yes
Module System
CommonJS, ESM
Node Version
20.18.1
NPM Version
10.8.2
Score
98.5
Supply Chain
99.2
Quality
84.1
Maintenance
100
Vulnerability
99.6
License
Releases
Contributors
Languages
TypeScript (100%)
Developer
gilbarbara
Download Statistics
Total Downloads
4,120,398
Last Day
7,016
Last Week
36,735
Last Month
122,727
Last Year
3,342,582
GitHub Statistics
12 Stars
164 Commits
1 Forks
5 Watching
1 Branches
1 Contributors
Package Meta Information
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
Total Downloads
Cumulative downloads
Total Downloads
4,120,398
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
Daily Downloads
Weekly Downloads
Monthly Downloads
Yearly Downloads
Dependencies
2
@gilbarbara/helpers
Collection of useful functions
Usage
1npm i @gilbarbara/helpers
1import { unique } from '@gilbarbara/helpers'; 2 3const password = unique(24, { includeSymbols: true }); 4console.log(password); // g9HBfQeeOgrP.V1?JhETxn9P
API
Arrays
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.
Type Definition
1interface SortFunction<T = string> { 2  (left: PlainObject, right: PlainObject): number; 3  (left: T, right: T): number; 4}
Example
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.
Type Definition
1interface SortFunction<T = string> { 2  (left: PlainObject, right: PlainObject): number; 3  (left: T, right: T): number; 4}
Example
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
ASYNC_STATUS
A constant with possible async statuses.
cors(data: any, statusCodeOrOptions: number | CorsOptions = 200): CorsResponse
Returns a CORS response.
Type Definition
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.
Type Definition
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.
Type Definition
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.
Date
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.
Type Definition
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}
Example
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.
Devices
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.
Formatters
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.
Type Definition
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.
Type Definition
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.
Functions
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.
Misc
conditional<TReturn>(cases: Array<Case<TReturn>>, defaultCase?: () => TReturn): TReturn | undefined
A replacement for switch statements with dynamic expressions cases.
Type Definition
1type Case<T = void> = [boolean, () => T];
Example
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.
Example
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.
Example
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.
Example
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.
Type Definition
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.
Type Definition
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.
Numbers
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.
Objects
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.
Example
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.
Type Definition
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.
Statistics
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.
Strings
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.
Validators
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}
License
MIT
No vulnerabilities found.
Reason
no dangerous workflow patterns detected
Reason
no binaries found in the repo
Reason
license file detected
Details
- Info: project has a license file: LICENSE:0
- Info: FSF or OSI recognized license: MIT License: LICENSE:0
Reason
packaging workflow detected
Details
- Info: Project packages its releases by way of GitHub Actions.: .github/workflows/main.yml:18
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
- Warn: 3 commits out of 17 are checked with a SAST tool
Reason
9 existing vulnerabilities detected
Details
- Warn: Project is vulnerable to: GHSA-grv7-fg5c-xmjg
- Warn: Project is vulnerable to: GHSA-3xgq-45jj-v275
- Warn: Project is vulnerable to: GHSA-952p-6rrq-rcjv
- Warn: Project is vulnerable to: GHSA-mwcw-c2x4-8c55
- Warn: Project is vulnerable to: GHSA-gcx4-mw62-g8wm
- Warn: Project is vulnerable to: GHSA-c24v-8rfc-w8vw
- Warn: Project is vulnerable to: GHSA-8jhw-289h-jh2g
- Warn: Project is vulnerable to: GHSA-4vvj-4cpr-p986 / GHSA-64vr-g452-qvp3
- Warn: Project is vulnerable to: GHSA-9cwx-2883-4wfx
Reason
Found 0/20 approved changesets -- score normalized to 0
Reason
detected GitHub workflow tokens with excessive permissions
Details
- Warn: no topLevel permission defined: .github/workflows/main.yml:1
- Info: no jobLevel write permissions found
Reason
dependency not pinned by hash detected -- score normalized to 0
Details
- Warn: third-party GitHubAction not pinned by hash: .github/workflows/main.yml:27: update your workflow using https://app.stepsecurity.io/secureworkflow/gilbarbara/helpers/main.yml/main?enable=pin
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/main.yml:32: update your workflow using https://app.stepsecurity.io/secureworkflow/gilbarbara/helpers/main.yml/main?enable=pin
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/main.yml:35: update your workflow using https://app.stepsecurity.io/secureworkflow/gilbarbara/helpers/main.yml/main?enable=pin
- Warn: third-party GitHubAction not pinned by hash: .github/workflows/main.yml:41: update your workflow using https://app.stepsecurity.io/secureworkflow/gilbarbara/helpers/main.yml/main?enable=pin
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/main.yml:52: update your workflow using https://app.stepsecurity.io/secureworkflow/gilbarbara/helpers/main.yml/main?enable=pin
- Warn: third-party GitHubAction not pinned by hash: .github/workflows/main.yml:70: update your workflow using https://app.stepsecurity.io/secureworkflow/gilbarbara/helpers/main.yml/main?enable=pin
- Info: 0 out of 3 GitHub-owned GitHubAction dependencies pinned
- Info: 0 out of 3 third-party GitHubAction dependencies pinned
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
security policy file not detected
Details
- Warn: no security policy file detected
- Warn: no security file to analyze
- Warn: no security file to analyze
- Warn: no security file to analyze
Reason
project is not fuzzed
Details
- Warn: no fuzzer integrations found
Score
3.7
/10
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