Giter VIP home page Giter VIP logo

neilveil / devils Goto Github PK

View Code? Open in Web Editor NEW
1.0 1.0 0.0 90 KB

A collection of useful front-end web development utility functions

Home Page: https://www.npmjs.com/package/devils

License: MIT License

JavaScript 3.92% TypeScript 96.08%
front-end frontend-development frontend-toolkit javascript-helpers javascript-toolkit utility-functions utility-library utils web-development-tools frontend-utilities

devils's Introduction

Devils ๐Ÿ› ๏ธ

A collection of useful front-end web development utility functions.

Usage Example ๐Ÿš€

import { delay } from 'devils'

..

await delay(2)

Content ๐Ÿ“ฆ

  • Storage Manager
  • Theme Manager
  • Query String Manager
  • Scroll Back
  • Delay
  • Add Plural Suffix
  • Get Ordinal Suffix
  • Select Random in Array
  • Copy to Clipboard
  • Sort Array of Objects
  • Arrange an Array
  • Remove Duplicates
  • Format Numbers with Commas
  • Get Uploaded Image Details
  • Audio Player
  • Request Module
  • Fuzzy Search in Array of Objects

Everything in less than <5KB.

Helpers ๐Ÿ› ๏ธ

Storage Manager ๐Ÿ—„๏ธ

The Storage Manager helpers streamline the process of reading and writing various data types to local storage, eliminating the need for manual stringification and parsing. Additionally, it handles any potential errors that may arise during these operations.

// Set data
storageManager.set('my-data', { name: 'neilveil' })

// Read data -> "neilveil"
storageManager.get('my-data')

// Return default value if not defined -> "User"
storageManager.get('my-data-2', 'User')

// Clear only 1 key
storageManager.clear('my-data')

// Clear all data
storageManager.clear()

Theme Manager ๐ŸŽจ

The Theme Manager provides seamless control over both light and dark themes for your application.

// Set last used theme if exists or set user preferred theme based on OS
themeManager.init()

// Get current theme
themeManager.get() // Last used theme or user preferred theme

// Get user preferred theme
themeManager.getPreferredTheme()

// Set light theme
themeManager.set('light')

// Set dark theme
themeManager.set('dark')

// Toggle theme
themeManager.toggle()

HTML structure

<html>
  <body data-theme="light">
</html>

Theme manager saves theme in local storage key 'APP_THEME'.

Query String Manager ๐Ÿงฎ

Enables the seamless passage of object data across pages via URL query strings.

// Generate query string to append in path
qsm.gen({ a: 1 }) // -> ?eyJhIjoxfQ==

Append it in path

<a href="/my-page?eyJhIjoxfQ==">New page</a>

Read data in /my-page

// Read data
console.log(qsm.read()) // -> { a: 1 }

// Read key "a"
console.log(qsm.read('a')) // -> 1

// Read key "b" & return default value 2 if not found
console.log(qsm.read('b', 2)) // -> 2

Append query string in url

qsm.gen({ a: 1 }, '/my-page') // -> /my-page?eyJhIjoxfQ== | { a: 1 }

Append query string & forward

qsm.fwd({ b: 2 }, '/my-page') // -> /my-page?eyJhIjoxLCJiIjoyfQ== | { a: 1, b: 2 }

React example

function MyPage() {
  const [a, setA] = useState(qsm.read('a', 0))

  return (
    <div>
      <Link to={qsm.gen({ a: 1 }, '/my-page')}>Profile</Link>
    </div>
  )
}

Delay โณ

Allow your code to pause execution for a specified duration. This is valuable for displaying loaders, preventing action clicks, implementing custom animations, and more.

// Wait for 2 seconds
await delay(2)

or

await delay(2000, true)

Add Plural Suffix ๐Ÿ“š

Maintains code cleanliness by handling the addition of plural suffixes (s & ies) without the need for extra conditional operators.

<div>0 {addPluralSuffix('apple', 0)}</div> // 0 apples
<div>1 {addPluralSuffix('apple', 1)}</div> // 1 apple
<div>2 {addPluralSuffix('apple', 2)}</div> // 2 apples

<div>0 {addPluralSuffix('entry', 0)}</div> // 0 entries
<div>1 {addPluralSuffix('entry', 1)}</div> // 1 entry
<div>2 {addPluralSuffix('entry', 2)}</div> // 2 entries

Get Ordinal Suffix of a Number ๐Ÿฅ‡

Streamlines your code by handling the addition of ordinal suffixes (e.g., "st", "nd", "rd", "th") without the need for extra conditional operators.

<div>1{getOrdinalSuffix(1)}</div> // 1st
<div>2{getOrdinalSuffix(1)}</div> // 2nd
<div>3{getOrdinalSuffix(1)}</div> // 3rd
<div>4{getOrdinalSuffix(1)}</div> // 4th

<div>101{getOrdinalSuffix(1)}</div> // 101st
<div>102{getOrdinalSuffix(1)}</div> // 102nd
<div>103{getOrdinalSuffix(1)}</div> // 103rd
<div>104{getOrdinalSuffix(1)}</div> // 104th

Select Random in Array ๐ŸŽฒ

Allows you to pick a random value from an array. This is handy for displaying diverse texts, values, colors, etc., each time a user loads the application.

const lines = ['Awesome product', 'Try once', 'Wonderful!']

..

<div>{getRandomInArray(lines)}</div>

Copy to Clipboard ๐Ÿ“‹

Copy any text value to clipboard.

copyText('This is some text!')

Clone Object ๐Ÿ‘ฅ

Create a new copy of Javascript Object.

const data = { a: 1 }

const data2 = cloneObject(data)
data2.a = 2

console.log(data.a, data2.a) // 1, 2

Sort Array of Objects ๐Ÿ”„

const data = [
  { id: 4, name: 'Neil Arya' },
  { id: 1, name: 'Jon Doe' }
]

sortObjects(data, 'id') // by "id"
sortObjects(data, 'name') // by "name"

Arrange an Array ๐Ÿ”„

const data = [
  { id: 4, name: 'Neil Arya' },
  { id: 1, name: 'Jon Doe' }
]

arrangeObjects([1, 4], data, 'id')

Remove Duplicates from an Array ๐Ÿ”„

const data = [
  { id: 4, name: 'Neil Arya' },
  { id: 1, name: 'Jon Doe' },
  { id: 1, name: 'Jon Doe' }
]

removeDuplicates(data, 'id')

Round number ๐Ÿ”ต

roundNumber(2.343) // 2.34
roundNumber(2.326) // 2.33

// 1 decimal digit
roundNumber(2.326, 1) // 2.3

Decimal numbers should always be passed through this utility function to resolve floating point issues like .1 + .2 => 0.30000000000000004

Format Numbers with Commas ๐Ÿ’น

formatNumber(1000000) // 1,000,000

// Indian style formatting
formatNumber(1000000, true) // 10,00,000

Empty check ๐Ÿ“ฅ

Set default value if undefined emptyCheck(value, defaultValue).

let a = 1
let b

emptyCheck(a, 2) // 1
emptyCheck(b, 0) // 0

Get Uploaded Image Width, Height & Size ๐Ÿ–ผ๏ธ

Get uploaded image details to validate resolution & size.

getImgDetails(imageBlob) // { width: 1920, height: 1080, size: 1000000 }

Audio Player ๐ŸŽต

Pre-load & play sound in different browsers.

// Pre-load
audioPlayer('https://www.example.com/sound.mp3', 'load')

// Play
audioPlayer('https://www.example.com/sound.mp3')
// or
audioPlayer('https://www.example.com/sound.mp3', 'play')

// Pause
audioPlayer('https://www.example.com/sound.mp3', 'pause')

// Stop
audioPlayer('https://www.example.com/sound.mp3', 'stop')

Request Module ๐Ÿ“ก

await request({
  host: 'https://www.example.com', // *required
  path: '/api/profile', // *required
  method: 'get', // get | post | put | patch | delete
  args: { a: 1 }, // Used as "params" if get requests & "data" if post request
  headers: { authorization: 'Basic jgjklewr423452vnjas==' },
  params: { b: 2 }, // Get request parameters
  data: { c: 3 }, // Post request data
  clean: true // Default true, if true returns `response.data` & if false returns `response`
})

Dependency axios

<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/axios.min.js"></script>

Fuzzy Search in Array of Objects ๐Ÿ”

const data = [
  { id: 4, name: 'Neil Arya', keywords: ['developers', 'open-source'] },
  { id: 1, name: 'Jon Doe', keywords: ['dummy', 'user'] }
]

const searchKeys = ['name', 'keywords']

const searchString = 'neel ara'

console.log(fuse(data, searchKeys, searchString))

// Fuse options
const fuseOptions = {}
console.log(fuse(data, searchKeys, searchString, fuseOptions))

Dependency fuse.js

<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/fuse.min.js"></script>

Contributing ๐Ÿค

Contributions are welcome! Feel free to open an issue or submit a pull request.

License ๐Ÿ“œ

This project is licensed under the MIT License.

Developer ๐Ÿ‘จโ€๐Ÿ’ป

Developed & maintained by neilveil.

devils's People

Contributors

neilveil avatar

Stargazers

 avatar

Watchers

 avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.