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

simple-common-utils

v2.6.0

Published

A collection of utility classes.

Downloads

12,608

Readme

This is a collection of utility classes used for JS development.

  1. Usage
  2. Version history

Usage

  1. ArrayStringifier
  2. DottedStringObject
  3. StaticUtils

ArrayStringifier

Given an array, produces its string representation.

import { ArrayStringifier } from "simple-common-utils"; 
  • constructor()

    Constructs a class instance.

     new ArrayStringifier(array);

    gives exactly the same result as

     new ArrayStringifier()
         .setArray(array)
         .setSeparator(", ");
  • process() / toString()

    Returns a string representation of the array.

The following methods return this for method chaining.

  • setPrefix()

    Sets a prefix to be added to the resulting string.

     arrayStringifier.setPrefix(
         prefix, // String.
         addIfArrayLength // Boolean. If true the prefix will be added ONLY if the array is not empty. Default: true.
     );
  • setArray()

    Sets an array to stringify.

     arrayStringifier.setArray(array);
  • setSeparator()

    Sets a separator to be used.

     arrayStringifier.setSeparator(
         separator // String
     );
  • setElementProcessor()

    Sets an element processor for fine-grained per-element processing. An element processor is a function the return value of which will be used to determine the value and optionally the separator for the current array element. If an element processor returns an object with methods getElement() and getSeparator() they will be used to get the value and the separator for the current array element. If the method getElement() is not present in the return value, the latter will be used as the value for the current array element as is and the separator set by setSeparator() will be used.

     const arrayStringifier = new ArrayStringifier();
        
     arrayStringifier
         .setArray([1, 2, 3, 4])
         .setElementProcessor(element => element % 2 ? "Something odd" : element)
         .process(); // Something odd, 2, Something odd, 4
        
     arrayStringifier
         .setArray([1, 2, 3, 4])
         .setElementProcessor(element => !(element % 2) ? element : element == 1 ? {
             getElement() {
                 return "";
             },
             getSeparator() {
                 return "";
             }
         } : "Something odd")
         .process(); // 2, Something odd, 4
  • setPostfix()

    Sets a postfix to be added to the resulting string.

     arrayStringifier.setPostfix(
         postfix, // String.
         addIfArrayLength // Boolean. If true the postfix will be added ONLY if the array is not empty. Default: true.
     );

DottedStringObject

Provides a way to get and set objects properties with dot separated strings. All methods are static.

import { DottedStringObject } from "simple-common-utils";
  • getProperty()

    Gets a property value.

     DottedStringObject.getProperty(
         object, // Object.
         fullPropertyName, // String. A dot separated full property name.
         defaultValue // Object. This value is returned if the property doesn't exist.
     );

    Example:

     const const obj = {
         f1: 10,
         obj1: {
             f1: 20
         }
     };
        
     DottedStringObject.getProperty(obj, "f1"); // 10
     DottedStringObject.getProperty(obj, "f1", "aaa"); // 10
     DottedStringObject.getProperty(obj, "obj1.f1"); // 20
     DottedStringObject.getProperty(obj, "obj1.f2", "default"); // default
  • setProperty()

    Sets a property value.

     DottedStringObject.setProperty(
         object, // Object.
         fullPropertyName, // String. A dot separated full property name.
         value // Object. A value to set.
     );

    Example:

     const obj = {};
        
     DottedStringObject.setProperty(obj, "f1", 10); // { f1: 10 }
     DottedStringObject.setProperty(obj, "obj1", 20); // { f1: 10, obj1: 20 }
     DottedStringObject.setProperty(obj, "obj1", {}); // { f1: 10, obj1: {} }
     DottedStringObject.setProperty(obj, "obj1.f2", 30); // { f1: 10, obj1: { f2: 30 } }

StaticUtils

A collection of different utility methods. All the methods in this class are static.

import { StaticUtils } from "simple-common-utils";
  • color()

     StaticUtils.color("pink"); // 0xffc0cb00
        
     StaticUtils.color("non-existent-color"); // undefined
        
     StaticUtils.color(123); // 123
  • deg2Rad()

    Converts degrees to radians.

  • encodedUtf8ToByteArray()

    Converts the passed utf8-encoded string to a byte array.

     import utf8 from "utf8";
        
     StaticUtils.encodedUtf8ToByteArray(
         utf8.encode("abcфыва")); // [ 97, 98, 99, 209, 132, 209, 139, 208, 178, 208, 176 ]
  • ensureBounds()

    Ensures min <= value <= max.

     StaticUtils.ensureBounds(value, min, max);
        
     StaticUtils.ensureBounds(10, 2, 18); // 10
     StaticUtils.ensureBounds(100, 2, 18); // 18
     StaticUtils.ensureBounds(100, 200, 1800); // 200
  • escapeRegExp()

    Given a string, escapes all occurences of symbols that have special meaning in regular expressions. The code is taken from here.

     StaticUtils.escapeRegExp("a"); // a
     StaticUtils.escapeRegExp("*a^"); // \*a\^
  • formatError(error)

    Enumerates the fields of the given argument with Object.entries() and returns a string based on the result. Returns the given argument if it has no enumerable entries.

  • getRandomColor()

    Returns a random color in the form "#RRGGBB".

  • objectToArray()

    Converts object to an array and returns it. Nested objects are not parsed.

     StaticUtils.objectToArray({a: "10", b: 20}); // [ '10', 20 ]
     StaticUtils.objectToArray({a: "10", b: 20, c: {a: 10}}); //  [ '10', 20, { a: 10 } ]
  • pushAndReturnElement()

    Pushes element to array and returns element.

     StaticUtils.pushAndReturnElement(array, element);
  • quoteIfString()

    Quotes value if it's a string, using quotingSymbol.

     StaticUtils.quoteIfString(10); // 10
     StaticUtils.quoteIfString("10"); // "10"
     StaticUtils.quoteIfString("10", "'"); // '10'
  • random()

    Generates a random number using Math.random().

     StaticUtils.random(1.5, 2.5); // A random number between 1.5 and 2.5.
        
     StaticUtils.random(10, 12, true); // An integer random number in the half-open range [10, 12).
        
     StaticUtils.random(10, 12, true, true); // An integer random number in the closed-range [10, 12].
  • replaceAll()

    Implements a "replace all" functionality for a string. The code is taken from here.

     StaticUtils.replaceAll("abc", "b", "10"); // a10c
     StaticUtils.replaceAll("a^b*c", "^b", "10"); // a10*c
  • round()

    Rounds value to decimals digits after the decimal point (thanks, MarkG!). symmetric is used to achieve the same functionality both for negative and positive numbers.

     StaticUtils.round(value, decimals, symmetric);
    
     StaticUtils.round(10.2); // 10.2
     StaticUtils.round(10.2, 0); // 10
     StaticUtils.round(10.5, 0); // 11
     StaticUtils.round(10.523, 1); // 10.5
     StaticUtils.round(10.525, 2); // 10.53
     StaticUtils.round(-1.5, 0); // -1
     StaticUtils.round(-1.5, 0, true); // -2
  • safeQuoteIfString()

    Invokes quoteIfString() passing value and quotingSymbol to it if quoteIfString is true.

     StaticUtils.safeQuoteIfString(value, quoteIfString, quotingSymbol);
  • today(returnNow = false)

    Returns a Date object, representing today, if returnNow is false. Returns [now, today] otherwise.

  • verify(condition, errorMessage)

    Evaluates the passed boolean condition and throws an error with the errorMessage text if condition is false.

Version history

Version number|Changes -|- v2.6.0|StaticUtils.getRandomColor() added. v2.5.1|StaticUtils.formatError(): fallback added. v2.5.0|StaticUtils.formatError() added. v2.4.0|1. StaticUtils.today(): returnNow added.2. package.json: fields alphabetized. v2.3.0|StaticUtils.today() added. v2.2.0|./js/processing-queue/ classes are added. v2.1.1|1. StaticUtils.verifyPropertyPresence() behaved incorrectly if a field being verified was null or undefined. Fixed.2. Final stops removed from throw messages. v2.1.0|StaticUtils.verifyPropertyPresence() / StaticUtils.verifyPropertyAbsence() are added. v2.0.0|Backwards-incompatible changes in data-transmission-protocol classes:1. Packet.constructor() changed and Packet.wrap() added.2. Format is filled dynamically: it's necessary to import relevant format-defining classes. v1.7.1|Autobinding removed from the data-transmission-protocol classes. v1.7.0|data-transmission-protocol-classes added. These deprecate zx55. v1.6.0|zx55 added. v1.5.1|quotingSymbol is added to StaticUtils.quoteIfString() / safeQuoteIfString(). v1.4.1|The method StaticUtils.verify() is added. v1.2.1|StaticUtils.colorNames had 00 as alpha. Changed to FF. v1.2.0|The parameter symmetric is added to StaticUtils.round() in a backwards-compatible way. v1.1.0|The methods StaticUtils.deg2Rad() and StaticUtils.color() are added. v1.0.0|Initial release.

Written with StackEdit.