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

safely-iterate

v1.0.1

Published

Fail-safe optimized array iteration utilities for reactive environments.

Downloads

23

Readme

safely-iterate

🌱 Fail-safe optimized array iteration utilities for reactive environments.

✨ Features

  • 📦 ~400b (gzipped)
  • 🙅‍♂️ Zero dependencies
  • 🌈 TypeScript Support
  • ✅ Fully tested and reliable
  • 🎁 Works with NodeList and HTMLCollection
  • ⚒ CommonJS, ESM & browser standalone support

🔧 Installation

You can easily install this package with yarn or npm:

$ yarn add safely-iterate

or

$ npm install --save safely-iterate

🤷‍♂ Why this?

If you've worked with JavaScript well enough, I bet you're familiar with errors like "TypeError: Cannot read property 'map' of undefined". Now, this can occur due to several reasons like unpredictable data response from an API, delayed arrival of data etc.

With JavaScript apps dominating the web today, this can be quite costly as it could result in several problems like CSR interruption, broken server-side rendering and the worst of them all - unusable systems.

This library exists to provide a solution by offering re-usable utilities intentionally optimized to fail gracefully and leverage a pass-first-replace-later strategy which only works in reactive environments. As a bonus, you can use the functions to iterate over NodeList and HTMLCollection without worrying about cross-browser compat.

📖 Usage

To start with, this library exposes the safe functions safeEvery, safeFilter, safeFind, safeFindIndex, safeForEach, safeMap, safeReduce, safeReduceRight, safeSome and safeSort.

The common signature for all safe functions excluding safeReduce and safeReduceRight look something like:

function safeFn<T>(
  array: T[] | NodeList | HTMLCollection,
  // Here, `any` is the actual callback return value of the safe function being used.
  callbackfn: (value: T, index: number, obj: T[]) => any,
  thisArg?: any
)

// This variant is for when a non-array is passed to the safe function
function safeFn<T>(
  array: T,
  // Here, `any` is the actual callback return value of the safe function being used.
  callbackfn: (value: undefined, index: undefined, obj: never[]) => any,
  thisArg?: any
)

See index.d.ts for more information on safeReduce, safeReduceRight and the signatures of all the safe functions.

In the example below, regardless of what type items in state is, it gracefully gets converted to an array internally, which also means even if the type gets polluted sometime in the future of the component's existence, safeMap will retain its internal type of array.

However, as long as items is an array in the component, any time it's updated, safeMap will react to that change and display the updated items. Same applies for safeEvery, safeFilter etc.

Example

import { useEffect, useCallback } from 'react'
import { safeMap } from 'safely-iterate'

function ItemList() {
  const [items, setItems] = useState([])
  const [isLoaded, setIsLoaded] = useState(false)
  const getItems = useCallback(() => {
    return fetch('https://api.example.com/items').then(res => res.json())
  }, [])

  useEffect(() => {
    ;(async function () {
      const result = await getItems()
      setIsLoaded(true)
      setItems(result.items)
    })()
  }, [])

  if (!isLoaded) return <div>Loading...</div>
  return (
    <ul>
      {safeMap(items, item => {
        if (!item) return
        return (
          <li key={item.name}>
            {item.name} {item.price}
          </li>
        )
      })}
    </ul>
  )
}

🤝 License

MIT © Olaolu Olawuyi