0.15.2 • Published 1 year ago

@rashedmakkouk/dev-utils v0.15.2

Weekly downloads
-
License
BSD 3-Clause
Repository
github
Last release
1 year ago

Dev Utils

Utility library.

v0.15.0

Notable changes in v0.15.0:

  • Added decimal and precision options support to number type in random helper.
  • Updated random usage instructions in README.md.
  • Renamed toNumber option to parseNumber in toArray helper (Breaking change).
  • Refactored date argument to accept empty value in timestamp, defaults to Now.
  • Added keyExtractor helper usage instructions in README.md.
  • Added abs support to math option in toNumeric.
  • Added precision option in toNumeric.
  • Added function @returns tag and description to all helpers.
  • Code updates and enhancements.

Check out CHANGELOG.md for a full list of changes.

Installation

Install package in your project.

# NPM
npm install @rashedmakkouk/dev-utils

# Yarn
yarn add @rashedmakkouk/dev-utils

Usage

This package can be used in both the browser and Node.js projects.

Using ES6 module syntax

import { module } from '@rashedmakkouk/dev-utils';

module();

Using CommonJS syntax

const { module } = require('@rashedmakkouk/dev-utils');

module();

Methods

autolinks

Parses a text string and returns links matching:

  • Hashtag #
  • Mention @
  • URL http

Builds on autolinker with custom configuration and output.

Parameters

ParamTypeRequiredDefaultDescription
textstringNo''Text to parse.

Returns

  • (Object.links): Array of unique words links (e.g. mention, hashtag, url).
  • (Object.matches): Array of all matched links metadata.

Example

autolinks('The #quick brown @fox.');
// Result.
{
  links: [
    "#quick",
    "@fox"
  ],
  matches: [
    {
      "__jsduckDummyDocProp": null,
      matchedText: "#quick",
      offset: 4,
      tagBuilder: {
        newWindow: true,
        truncate: {
          length: null,
          location: "end"
        },
        className: ""
      },
      serviceName: "twitter",
      hashtag: "quick"
    },
    {
      "__jsduckDummyDocProp": null,
      matchedText: "@fox",
      offset: 17,
      tagBuilder: {
        newWindow: true,
        truncate: {
          length: null,
          location: "end"
        },
        className: ""
      },
      serviceName: "twitter",
      mention: "fox"
    }
  ]
}

delay (Promise)

Delays executions of a specified piece of code.

Parameters

ParamTypeRequiredDefaultDescription
msnumberYes-Duration to delay in milliseconds.
racebooleanNofalseIf true, returns a Promise object that is rejected with status 408 Request Timeout.

Returns

  • (Object): Returns Promise Object,.

Rejects

  • (Object): Rejects { status: 408, statusCode: 408 }.

Example

try {
  await delay(1000, true);
} catch (error) {
  // Handle rejected Promise.
}

escape

Sanitizes and formats SQL input data for safe use in MySQL query statements.

A sqlstring wrapper for convenience.

Parameters

ParamTypeRequiredDefaultDescription
valueAnyYes-Data to escape.
optionsobjectNo-Custom options to apply.
options.escapeIdbooleanNofalseEscapes Identifiers such as database table column names and reserved words.
options.parseIntegerbooleanNofalseParses values such as LIMIT and OFFSET.
options.stripQuotebooleanNofalseRemoves quotes from result; useful for RegExp or query conditions e.g. ASC.

Returns

  • (string): Returns escaped string.

Example

escape('abc', { stripQuote: true });
// Result.
abc

initials

Extracts the first character from the first and last words in a string.

Splits at: Splits at: white space, comma, dot, pipe, underscore, dash.

Parameters

ParamTypeRequiredDefaultDescription
textstringNo''Text to extract characters from.

Returns

  • (string): Returns extracted characters as string.

Example

initials('John Unknown-Doe');
// Result.
'JD'

isBase64

Validates if supplied mime type and/or base64 string are valid.

Parameters

ParamTypeRequiredDefaultDescription
valuestringYes-Base64 value.
optionsobjectNo-Custom options to apply.
options.allowEmptybooleanNofalseReturns true if value is empty.
options.allowMimebooleanNofalseString may include mime type.
options.mimeRequiredbooleanNofalseString should include mime type.
options.urlSafebooleanNofalseSee Base64URL.

Returns

  • (boolean): Returns 'true' if supplied string passes checks, else 'false'.

Example

isBase64('data:image/png;base64,<code>', { mimeRequired: true });
// Result.
true

isValid

Verifies if supplied payload is valid by defined type.

Parameters

ParamTypeRequiredDefaultDescription
isTypeofstringYes-string, array, number, object, jsonStr.
valueAnyNo-Data to validate.
optionsobjectNo-Custom options to apply.
options.allowEmptybooleanNofalseIf true, validates empty, null, undefined and 0 values as valid.

Returns

  • (boolean): Returns true if supplied payload passes checks, else false.

Example

isValid('string', 'undefined');
// Result.
false

isValid('string', '', { allowEmpty: true });
// Result.
true

isValid('number', 'abc');
// Result.
false

isValid('number', '123');
// Result.
false

isValid('number', 0, { allowEmpty: true });
// Result.
true

isValid('number', 0);
// Result.
false

isValid('object', ['abc']);
// Result.
false

isValid('object', {}, { allowEmpty: true });
// Result.
true

joinPath

Joins a list of absolute and relative paths as a string.

Parameters

ParamTypeRequiredDefaultDescription
segmentsArrayYes-List of paths to join.
optionsobjectNo-Custom options to apply.
options.resolvebooleanNofalseIf true, tries to resolve segments into an absolute path.

Returns

  • (string): Returns joined path string.

Example

joinPath(['/foo', 'bar', 'baz\\abc', './def', '..']);
// Result.
'/foo/bar/baz/abc'

keyExtractor

For applications where unique keys need to be generated for elements in an array (e.g. React Native FlatList).

Parameters

ParamTypeRequiredDefaultDescription
keystring | numberYes-Can be any value (e.g. id, title).
indexnumberYes-Element array index.

Returns

  • (string): Returns concatenated 'key-index' string.

Example

keyExtractor('post', 2);
// Result.
'post-2'

letterCase

See Start Case for more details.

Formats supplied string to defined case.

Parameters

ParamTypeRequiredDefaultDescription
textstringYes-Text to format.
optionsobjectYes-Custom options to apply.
options.letterCasestringYes-lower, upper, sentence, kebab, title.
options.separatorsArrayNo-Replaces specified symbols with white space.

Returns

  • (string): Returns formatted string.

Example

letterCase('_the   quiCK--brown     FOx_!', { letterCase: 'sentence' });
// Result.
'_The   quick--brown     fox_!'

letterCase('the #quiCK brown FOx!', { letterCase: 'kebab' });
// Result.
'the-quick-brown-fox'

// Applies custom separators if supplied, else defaults to: [_-\s]+
letterCase('_the   quiCK--brown     FOx_!', { letterCase: 'title' });
// Result.
'The Quick Brown Fox!'

ms

Parses a number representation or a string time period (e.g. 1h, 2d) to Unix Timestamp.

  • ms: millisecond.
  • s: second.
  • m: minute.
  • h: hour.
  • d: day.
  • w: week.
  • y: year.

Parameters

ParamTypeRequiredDefaultDescription
spanstring | numberYes-ms, s, m, h, d, w, y.

Returns

  • (number): Returns time representation in milliseconds, else parses value as integer.

Example

ms('1hr');
// Result.
3600

ms('1000');
// Result.
1000

normalize

Normalizes payload by defined object attribute.

Payload data needs to be consistent and has similar data structure to avoid unexpected results, specifically defined idAttribute (e.g. results from a database query).

Parameters

ParamTypeRequiredDefaultDescription
keystringYes-Object property name to move records to.
payloadArray | objectYes-Data to normalize.
optionsobjectNo-Custom options to apply.
options.idAttributestringNoidObject property name to normalize records based on.

Returns

  • (Object.entities): Normalized records by 'key'.
  • (Object.result): Array or single value of data 'idAttributes'.

Example

// Array payload.
normalize('posts', [{ id: 1, title: 'abc' }, { id: 2, title: 'def' }], { idAttribute: 'uid' });
// Result.
{
  entities: {
    posts: {
      1: { uid: 1, title: 'abc' },
      2: { uid: 2, title: 'def' }
    },
  },
  result: [1,2]
}

// Object payload.
normalize('posts', { id: 1, title: 'abc' });
// Result.
{
  entities: {
    posts: {
      1: { id: 1, title: 'abc' }
    },
  },
  result: 1
}

parseUrl

Parses URL string segments including query string values, if any.

A url-parse wrapper for convenience and extensibility.

Parameters

ParamTypeRequiredDefaultDescription
urlstringYes-URL to parse.

Returns

  • (Object): Returns parsed URL object.

Example

parseUrl('https://localhost:8000/foo/bar?firstName=John&lastName=Doe');
// Result.
{
  slashes: true,
  protocol: "https:",
  hash: "",
  query: {
    firstName: "John",
    lastName: "Doe"
  },
  pathname: "/foo/bar",
  auth: "",
  host: "localhost:8000",
  port: "8000",
  hostname: "localhost",
  password: "",
  username: "",
  origin: "https://localhost:8000",
  href: "https://localhost:8000/foo/bar?firstName=John&lastName=Doe"
}

random

Generates a random string or number with customizable options.

  • filename: File names stored in databases.
  • number: Number between defined min and max (See Math.random).
  • temp: File names stored in temporary or cache locations.
  • title: Content or post random title.
  • uuid: v4.

This helper uses uuid to generate UUIDs in options filename, temp and uuid; for known issues, see Duplicate UUIDs (Googlebot).

Usage

If you are using this package in a React Native/Expo project:

  1. Install react-native-get-random-values polyfill.
  2. Add import 'react-native-get-random-values' as the first line in your index/entry point. See more details here.

Parameters

ParamTypeRequiredDefaultDescription
typestringYes-filename, number, title, temp, uuid.
optionsobjectNo-Custom options to apply.
Options: number
ParamTypeRequiredDefaultDescription
options.minnumberNo0If type is number, minimum value to start from.
options.maxnumberNo1If type is number, maximum value to end at.
options.decimalbooleanNofalseGenerate a random number with decimals.
options.precisionnumberNo0Limit generated number decimal places.
Options: filename, temp, title
ParamTypeRequiredDefaultDescription
options.prefixstringNo-Text to add to the beginning of the result.
options.suffixstringNo-Text to add to the end of the result.
Options: uuid
ParamTypeRequiredDefaultDescription
optionsundefined--Argument not available for 'uuid' option.

Returns

  • (string|number): Returns generated string or number.

Example

random('number', { min: 1000, max: 2000 });
// Result.
1784

random('number', { decimal: true, min: 10, max: 200, precision: 2 });
// Result.
97.13

random('filename', { prefix: 'post' });
// Result.
'post_2018-01-01_12-00-00_7f2a79ba-962e-4b35-96d0-28xf1d025107'

random('temp');
// Result.
'2018-01-01_12-00-00_efc7438f-0a4d-4538-af87-b6984xe04688'

random('title', { suffix: 'post' });
// Result.
'2018-01-01_12-00-00_post'

random('uuid');
// Result.
'7e0ea78d-c170-4449-93fb-f5caxb952752'

sanitize

Trims extra whitespace and removes HTML tags.

Uses: trimWhitespace

Parameters

ParamTypeRequiredDefaultDescription
textstringYes-Text to trim.

Returns

  • (string): Returns sanitized string.

Example

sanitize('<script>"the__   #quicK-- BROWN     @foX_".js</script> <html><div>Html code</div></html>');
// Result.
'the__ #quicK-- BROWN @foX_.js Html code'

singular

Trims last character if ends with 's' or replaces 'ies' with 'y'.

Not an ideal solution, but does the job for most cases.

Parameters

ParamTypeRequiredDefaultDescription
textstringYes-Text to convert.

Returns

  • (string): Returns trimmed text.

Example

singular('posts');
// Result.
'post'

singular('commodities');
// Result.
'commodity'

splitArray

Splits any array to chunks by supplied size.

Parameters

ParamTypeRequiredDefaultDescription
arrayArrayYes-Data array to split.
sizenumberNo-Size of each array chunk; bypasses split if empty.

Returns

  • (Array): Returns new array chunks.

Example

splitArray([{ id: 1, title: 'abc' }, { id: 2, title: 'def' }]);
// Result.
[
  { "id": 1, "title": "name1" },
  { "id": 2, "title": "name2" }
]

splitArray([{ id: 1, title: 'abc' }, { id: 2, title: 'def' }], 1);
// Result.
[
  [{ "id": 1, "title": "name1" }],
  [{ "id": 2, "title": "name2" }]
]

timestamp

Parses any date value to a timestamp with predefined or custom format.

  • datetime: dddd, MMMM D at h:mA.
  • fromNow: Relative time.
  • short: ddd, MMM D.
  • sql: YYYY-MM-DD HH:mm:ss.

You can use 'format' option to provide custom date/time format.

Parameters

ParamTypeRequiredDefaultDescription
datestring | number | objectNoDate.now()Date string, Date object, Unix Timestamp.
optionsobjectNo-Custom options to apply.
options.formatstringNoDD/MM/YYYYdatetime, fromNow, short, sql, Moment.

Returns

  • (string): Returns formatted timestamp.

Example

timestamp();
// Result.
'31/12/2022' // Date.now()

timestamp(new Date('12/31/2022'), { format: 'datetime' });
// Result.
'Saturday, December 31 at 12:00AM'

timestamp(Date(), { format: 'fromNow' });
// Result.
'a few seconds ago'

timestamp(moment('12/31/2022'), { format: 'short' });
// Result.
'Sat, Dec 31 12:00AM'

timestamp('12/31/2022 12:00', { format: 'sql' });
// Result.
'2022-12-31 12:00:00'

toArray

Converts any value to array.

Useful for multi value fields as 'group_concat'.

Uses: trimWhitespace

Parameters

ParamTypeRequiredDefaultDescription
valueAnyYes-Data to convert.
optionsobjectNo-Custom options to apply.
options.separatorstringNo,The pattern where the split should occur.
options.parseNumberbooleanNofalseIf true, maps array values as Number.

Returns

  • (Array): Returns new array based on supplied options.

Example

toArray('1', { parseNumber: true });
// Result.
[1]

toArray(['a', 'b', 'c']);
// Result.
['a', 'b', 'c']

toArray({ id: 1, title: 'name-1' });
// Result.
[{ id: 1, title: 'name-1' }]

toArray('1,2,3');
// Result.
['1', '2', '3']

toArray('  a-2-3  -', { parseNumber: true, separator: '-' });
// Result.
[NaN, 2, 3]

toNumeric

Converts value to and validates as 'number'.

Parameters

ParamTypeRequiredDefaultDescription
valuenumber | stringYes-Number representation; if null, returns 0.
optionsobjectNo-Custom options to apply.
options.decimalbooleanNotrueIf true, retains decimal point.
options.mathstringNo-'abs', 'ceil', 'floor', 'round', 'trunc'.
options.precisionnumberNo-If supplied, limits number decimal places.

Returns

  • (number): Returns formatted number.

Example

toNumeric('1.3');
// Result.
1.3

toNumeric(1.3);
// Result.
1.3

toNumeric('1.3', { decimal: false });
// Result.
1

toNumeric('1.3456', { precision: 2 });
// Result.
1.35

toNumeric('1.3446', { precision: 2 });
// Result.
1.34

toNumeric('1.3', { math: 'ceil' });
// Result.
2

toNumeric(1.3, { math: 'floor' });
// Result.
1

toNumeric(['1.3', 1], { math: 'floor' });
// Result.
NaN

toNumeric({ 0: 1 });
// Result.
NaN

toRGBa

Converts color from 'keyword' (e.g. green) or 'hex' (e.g. #00FF00) to RGBa value. Useful when there is a need to apply color opacity.

Parameters

ParamTypeRequiredDefaultDescription
colorstringYes-Can be Name or HEX code (e.g. white, #DDD).
alphanumberNo1Set color opacity value.

Returns

  • (string): Returns RGBa value for valid colors else 'rgba(0,0,0,alpha)'.

Example

toRGBa('purple');
// Result.
'rgba(128,0,128,1)'

toRGBa('#DDD', 0.5);
// Result.
'rgba(221,221,221,0.5)'

toRGBa('invalidColor', 0.3);
// Result.
'rgba(0,0,0,0.3)'

trimWhitespace

Removes leading and trailing spaces and replaces multiple white spaces, tabs and newlines with one space.

Parameters

ParamTypeRequiredDefaultDescription
textstringYes-Text to trim.

Returns

  • (string): Returns trimmed text.

Example

trimWhitespace('   _the   quiCK--brown     FOx !');
// Result.
'_the quiCK--brown FOx !'

Changelog

Check out CHANGELOG.md for a full list of changes.

Community

Head over to Discussions where you can ask questions, request new features or voice your ideas and suggestions.

Found a bug or you have an improvement recommendation, head over to Issues and submit a new request.

License

This package is available under the BSD 3-Clause license. It also includes external libraries that are available under a variety of licenses. See LICENSE for the full license text.

0.14.9

1 year ago

0.15.0

1 year ago

0.15.1

1 year ago

0.15.2

1 year ago

0.14.7

2 years ago

0.14.8

2 years ago

0.14.6

2 years ago

0.14.5

2 years ago

0.14.4

2 years ago

0.14.3

2 years ago

0.14.2

2 years ago

0.14.1

2 years ago

0.14.0

2 years ago

0.13.2

2 years ago

0.13.1

2 years ago

0.13.0

2 years ago

0.12.0

2 years ago