npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@wilfredlopez/react-utils

v3.0.8

Published

Utility functions and types for Javascript projects

Downloads

10

Readme

Javascript Utility Functions

Install

NPM
npm install @wilfredlopez/react-utils
Script Tag
<script src="https://unpkg.com/@wilfredlopez/react-utils@latest/dist/index.umd.js"></script>
<script type="text/javascript">
  console.log(ReactUtils.Cipher)
</script>
ES6

Validator

import { Validator } from "@wilfredlopez/react-utils"

Validator.isEmail('bad@notemail'); //false
Validator.isEmail('[email protected]'); //true
Validator.isNotEmptyString(""); //false
Validator.isNotEmptyString("some data")); //true
Validator.isDate("10/20/2020", "MM/DD/YYYY") //true
Validator.isDate("2020/01/01") //true;
Validator.isDate("anyInvalidDate") //false;
Validator.isInt("2.1") //false
Validator.isPort(5000) //true
Validator.isPort(10.1) //false
Validator.isPort(80000000) //false
Validator.isURL("https://www.wilfredlopez.net") //true
Validator.isURL("www.test.com")//true
Validator.isURL("www.test.") //false

memoize

import { memoize } from '@wilfredlopez/react-utils'

const fibMemo = memoize(function (n: number): number {
  if (n <= 2) return 1
  return fibMemo(n - 1) + fibMemo(n - 2)
})

console.log(fibMemo(20)) //6765
console.log(fibMemo(30)) //832040
console.log(fibMemo(20)) //6765;
console.log(fibMemo(100)) //354224848179262000000
console.log(
  fibMemo.cache.size //100
)

Mapper

import { Mapper } from '@wilfredlopez/react-utils'

const initialData = {
  test1: 1,
  test2: 2,
}
const dataMap = new Mapper<number, string>(initialData)
console.log(dataMap.length) //2
console.log(dataMap.set('test3', 3).delete('test1')) //1
console.log(dataMap.has('test1')) //false
console.log(dataMap.get('test2')) //2
console.log(dataMap.isEmpty()) //false
dataMap.map(val => {
  console.log(val) // 2, 3
})

StringHelper & NumberHelper

import { StringHelper, NumberHelper } from '@wilfredlopez/react-utils'
StringHelper.slogify('hello world') //"hello-world";
StringHelper.toProperCase(' hello world 2') //" Hello World 2";
const pg = new PatternGenerator("'WL'-XXXXX")

const codes = []
console.log(pg.next) //WL-H2QDD
while (codes.length < 50) {
  codes.push(pg.next)
}
console.log(codes) //[ 'WL-H2QDD', 'WL-LHCO7', 'WL-0EFK6', 'WL-SQU7W',...,'WL-9NYHX' ]

NumberHelper.formatDuration(10000) //"02:46:40";
const arr = [...NumberHelper.range({ start: 0, end: 10 })]
console.log(arr) // [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ];

const iter = ArrayHelper.createReverseArrayIterator([1, 2, 3, 4])
for (let i of iter) {
  console.log(i) // 4,3,2,1
}
console.log(NumberHelper.isPrime(7)) //true
console.log(NumberHelper.isPrime(20)) //false

DeepCopy

import { deepCopy } from '@wilfredlopez/react-utils'

const originalUser = { name: 'SOMEONE' }
const original = { api: { db: { users: [{ user: originalUser }] } } }

const copy = deepCopy(original)
const regularCopy = Object.assign({}, data)
originalUser.name = 'FULANO'
console.log(copy.api.db.users[0].user.name) // SOMEONE (DEEP COPY)
console.log(original.api.db.users[0].user.name) // FULANO (MUTATED)
console.log(regularCopy.api.db.users[0].user.name) // FULANO (MUTATED)

Assertions

import {
  AssertionError,
  assert,
  assertIsString,
  forceString,
} from '@wilfredlopez/react-utils'

const error = new AssertionError('message')

const n = 1
function doSomething(value) {
  assert(typeof n === 'number')
  return n + 20
}
doSomething('string') //throws error

function sendMessage(message: any) {
  assertIsString(message) //throws error if not string
  message.trim() //will give you auto-complete for string type
}

assertNever

import { assertNever } from '@wilfredlopez/react-utils'
enum AppActions {
  'SET_STATE',
  'ADD',
  'REMOVE',
}
interface Actions {
  type: AppActions
  payload: any
}

export function myReducer(state = {}, action: Actions): {} {
  switch (action.type) {
    case AppActions.SET_STATE:
      return { ...state, ...action.payload }
    case AppActions.ADD:
      return { ...state }
    case AppActions.REMOVE:
      return {
        ...state,
      }
    default:
      assertNever(action.type, 'Not all actions are being handled.')
      return state
  }
}

Random Generator (for test data)

import { RandomGenerator } from '@wilfredlopez/react-utils'

const dg = new RandomGenerator({
  animals: ['dog', 'panda', 'cat'],
})

console.log(dg.from('animals')) //cat
console.log(dg.from('animals')) //dog

IndexDB Store

import { indexDBStore } from '@wilfredlopez/react-utils'

const store = indexDBStore.createStore('WDB', 'myStore', {
  version: 1,
  onupgradeHandler: (store, request, event) => {
    //do transactions that can only happen on upgrade events.
    store.createIndex('IdIndex', 'id', { unique: true })
    console.log(request, event)
  },
})

//write
store.readwrite(db => {
  db.add({ id: '1', name: '1 name' }, '1')
  db.add({ id: '2', name: '2 name' }, '2')
})

//get all entries
store.entries().then(data => {
  console.log({ entries: data })
})

//get all values
store.values().then(values => {
  console.log('values: ', { values })
})

//Read
store.readonly.get('2').then(value => {
  console.log('value with key 2 is: ', value)
})

//COUNT: Retrieve the number of records matching the given key

//COUNT: Object API
const range = IDBKeyRange.bound('0', '2')
store.count(range).then(result => {
  console.log(`count is : `, result)
})
//COUNT: Function API
store('readonly', db => {
  const request = db.count('2')
  request.onsuccess = function () {
    console.log(`count is : `, this.result)
  }
})

//delete
store.del('1').then(() => {
  console.log('Delete complete for key 1')
})

store.readonly.get('1').then(value => {
  console.log('value with key 1 is now: ', value)
})
//Clear all the data in store.
store.clear().then(() => {
  console.log('store is cleared.')
})

Other Utilities

  • [createGlobalStyle] - Append styles to document's head. you can pass a string or an object with CSSProperties as arguments.
import { createGlobalStyle } from '@wilfredlopez/react-utils'

/*
Appends to document's head
<style>
body{
  background-color: red;
}
</style>
*/

createGlobalStyle({
  body: {
    backgroundColor: 'red',
  },
})

//OR

createGlobalStyle(`
  body: {
    background: red;
  }
`)

AND MUCH MORE...