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

@haensl/services

v1.5.1

Published

Assorted JavaScript services.

Downloads

895

Readme

services

Assorted JavaScript services.

NPM

npm version CircleCI

Installation

Via npm

$ npm install -S @haensl/services

Via yarn

$ yarn add @haensl/services

Usage

  1. Install @haensl/services

  2. Use services in your code:

import { platform } from '@haensl/services';

if (platform.hasWindow) {
  // code that relies on existance
  // of a global window object
}

Available services

  • component: Wraps utility functions useful in a component context, e.g. generate stateful class names.
  • error: Wraps utility functions pertaining to Errors.
  • numbers: Wraps utility functions pertaining to numbers, e.g. generating random numbers.
  • platform: Wraps information about the platform, e.g. is there a window? what is the current scroll position? is there local storage? etc.
  • throttle: Wraps functionality to throttle function execution, e.g. debounce.

component service

The component service wraps utility functions useful when working with components.

Methods

Methods

className(states, basename, [separator = '--'])

Returns a class list string composed of the basename followed by the basename concatenated with any truthy properties in states, wherein the concatenation is separated by separator (default: two dashes, --).

Example
import React, { useState } from 'react';
import { component } from '@haensl/services';

const MyComponent = () => {
  const [isDoingStuff, setIsDoingStuff] = useState(false);

  // code manipulating isDoingStuff

  const cn = component.className({
    isDoingStuff
  }, 'MyComponent');

  // if isDoingStuff is true
  // cn === "MyComponent MyComponent--isDoingStuff"
  // else
  // cn === "MyComponent"

  return (
    <div className={ cn }> // className="MyComponent MyComponent--isDoingStuff"
      // ...
    </div>
  );
};
setInputValue(input, value)

Sets the value of an HTMLInputElement and triggers an 'input' event. This is for example useful in cases where frameworks' event management makes it hard to programmatically trigger events that adhere to the native JavaScript event behaviour.

Example
import React, { useEffect, useRef, useState } from 'react';
import { component } from '@haensl/services';

const MyComponent = ({
  defaultValue = '',
  onChange
}) => {
  const [value, setValue] = useState(defaultValue);
  const input = useRef();

  useEffect(() => {
    if (!input.current) {
      return;
    }

    component.setInputValue(input.current, defaultValue);
  }, [defaultValue]);

  return (
    <div>
      // ...
      <input
        ref={ input }
        onChange={ onChange }
        value={ value }
      />
    </div>
  );
};

error service>

The error service wraps utility functions pertaining to Errors.

Methods

Methods

async attachResponseToError(response, error)

Attaches HTTP Response meta data to an Error. This is an async operation.

Example

const response = await fetch('/some/api');

if (!response.ok) {
    const error = new Error('Failing to fetch from API!');

    // extract metadata such as headers, status, etc from response and attach to error object.
    await attach(response, error);

    throw error;
}

numbers service

The numbers service wraps utility functions pertaining to numbers, e.g. random number generation.

Methods

Methods

rand({ min = 0, max = 1 })

Returns a random floating point number between min (inclusive) and max (exclusive). Due to JavaScript rounding, the value will never equal max.

Example
import { numbers } from '@haensl/services';

// generates a random number between 0 (inclusive) and 1 (exclusive)
const n = numbers.rand();

// generates a random number between 1 (inclusive) and 300 (exclusive)
const k = numbers.rand({ min: 1, max: 300});
randInt({ min, max })

Returns a random integer number between min and max (inclusive).

Example
import { numbers } from '@haensl/services';

// generates a random number between 0 (inclusive) and 3 (inclusive)
const n = numbers.randInt({ min: 0, max: 3 });

platform service

The platform service wraps information about the current runtime platform, e.g. is there a window? what is the current scroll position? is there local storage? etc.

Properties

Methods

Properties

hasDocument

Boolean, indicating whether or not the current runtime provides a global document object.

Example
import { platform } from '@haensl/services';

if (platform.hasDocument) {
  // code that relies on global document object,
  // e.g.
  if (/utf-8/i.test(document.characterSet)) {
    // do stuff that requires utf-8 encoding
  }
}
hasDocumentElement

Boolean, indicating whether or not the current runtime provides a global document.documentElement object.

Example
import { platform } from '@haensl/services';

if (platform.hasDocumentElement) {
  // code that relies on the existence of document.documentElement,
  // e.g.
  if (!(document.documentElement instanceof HTMLHtmlElement)) {
    // do stuff the XML way, because we're not in an HTML document
  }
}
hasLocalStorage

Boolean, indicating whether or not the current runtime provides a global window.localStorage object.

Example
import { platform } from '@haensl/services';

if (platform.hasLocalStorage) {
  // code that relies on local storage,
  // e.g.
  window.localStorage.setItem('my-data', data);
} else {
  // code that saves data elsewhere
}
hasSessionStorage

Boolean, indicating whether or not the current runtime provides a global window.sessionStorage object.

Example
import { platform } from '@haensl/services';

if (platform.hasSessionStorage) {
  // code that relies on session storage,
  // e.g.
  window.sessionStorage.setItem('my-data', data);
} else {
  // code that saves data elsewhere
}
hasWindow

Boolean, indicating whether or not the current runtime provides a global window object.

Example
import { platform } from '@haensl/services';

if (platform.hasWindow) {
  // code that relies on the global window object,
  // e.g.
  myComponent.scrollX = window.scrollX + 100;
}

Methods

scrollPosition()

Returns an object with properties x and y reflecting the current scroll position if applicaple, null otherwise.

Example
import { platform } from '@haensl/services';

if (platform.hasWindow) {
  window.addEventListener('scroll', () => {
    console.log(platform.scrollPosition());
    // will print objects like
    // { x: 0, y: 10 }
  });
} else if (!platform.hasDocument) {
  console.log(platform.scrollPosition());
  // will print null since there is neither document nor window!
}

throttle service

The throttle service wraps functionality used to throttle function execution, e.g. debounce.

Methods

Methods

debounce(fn, debounceMs)

Returns a new function that debounces fn by debounceMs milliseconds. Debouncing means fn is only executed if there are no calls for debounceMs milliseconds.

Example
import { throttle, platform } from '@haensl/services';

if (platform.hasWindow) {
  // only logs when there are no calls
  // for 50 milliseconds
  const onScroll = throttle.debounce(() => {
    console.log(platform.scrollPosition());
  }, 50);

  window.addEventListener('scroll', onScroll);
}

Changelog

License