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

klingsten-snippets

v1.0.51

Published

simple Date, String, Log, Number typescript Snippets

Downloads

5,413

Readme

npm

Snippets for Typescript

Dates, Files, and string functions

Checksum

The shasum of this package was 0d9124d61ace018726d98de4fafbbde9d570e309

Install

npm install --save klingsten-snippets --latest

Dependencies

  • day.js

import

import { Numbers, Files } from "klingsten-snippets";
 
// -> or node:
const { Numbers, Log, Dates } = require('klingsten-snippets');  

Usage / API

Number

import { Numbers } from "klingsten-snippets";
  Numbers.roundWithPrecision ( number,  integer);    // ( 120.12323, 3) -> 120.123
  Numbers.isNumeric(input: any)                      // "d12.35"        -> false
  Numbers.round(n: number): number                   //  
  Numbers.getCounter()                               // returns int, starts 0 && increases by 1 

Files

// API
import { Files, IUploadFile } from "klingsten-snippets";

/** uploads files to the browser, and return IUploadFile[] */
public static async uploadFiles(filesInfo: File[]): Promise<IUploadFile[]> 

/** reads as a file async, encoded base 64 url */
public static async readFileAsync(file: File): Promise<string> {

Usage

HTML:
<input #file type="file" multiple (change)="upload(file.files)"> 

HTML -> example from Angular[v2+]
<div *ngFor="let file of files">
    <img src="{{file.data}}" height="100px" max-width="200">
</div>
// Typescript -> ex from Angular[v2+] Component 
files: IUploadFile[] = [];   // see interfaces below 

async upload(files:File[]) { 
  this.files = await Files.uploadfiles(files)
} 

Strings

// API

import { Strings } from "klingsten-snippets";  
  /** splits a string by delimiters (',' or ',') except when delimiters are two quotes (' ' or " ")  */
  Strings.splitExceptQuotes(s: string, delimitor1: string = ';', delimitor2: string = ','): string[]  

  /** This uses the DOM  Parser (available only in the the browser) */
  public static removeHtmlTags(html: string): string 

 
  /** strict convertion of a string to number, return NaN if string does not convert correctly*/
  Strings.stringToNumber("129.12", true);   
  // 2nd parameter -> true: isUkFormat (decimal .) or false: is DK format (decimal ,)
 
  /** splits name and emails into {name:string, email:string} object. */
  Strings.splitNameFromEmail(s: string): { name: string, email: string }

  /** get unique ID, uses EPOCH plus random number */
  Strings.uniqueID(): string

  /** remove illegal chars in email adress (think non ASCII), and goes lowercase */
  Strings.replaceIllgalCharsEmail(s: string): string  

 
 /** check if email address is valid  */
  Strings.isEmailValid(s: string): boolean          

Examples:


 const emailStr = ' "lars, K" <[email protected]>; [email protected], Bob, Lin <[email protected]> ';
 // note ',' or ';' between quotes (""), and delimtors ',' and ';'
 
 const nameEmailArr :  = Strings.splitNameFromEmail( emailStr );
  // in:  emailStr // see above 
  // out: 
  [ { name: "lars, K", email: "[email protected]" },
    { name: "",        email: "[email protected]"  },
    { name: "Bob, Lin",email: "[email protected]"  }
  ]  // 3 items
  
 const email0 = Strings.splitNameFromEmail(strArr[0]);   
 // in:  strArr[0] = '"lars, K" <[email protected]>'
 // out: email0 = {name:'lars, K', email:'[email protected]' }
   
 const email1 = Strings.splitNameFromEmail(strArr[1]);   
 // in:  strArr[1] = '[email protected]'
 // out: email1 = {name:'', email:'[email protected]' }

Dates

// - now uses UTC Dates only 
// - uses dayjs
import { Dates } from "klingsten-snippets";
  Dates.epochToIsoString   (number) : string   // ISO 8601 format '1970-01-01T00:00:00.000Z
  Dates.epochToISODateTime (number) : string   // ISO 8601 format '1970-12-24 00:00:00'
  Dates.parseStrToDateUtc(dateStr: string, dateFormat: string) : Date | undefined
  Dates.parseStrToDateTimeUtc(dateStr: string, dateFormat: string) : Date | undefined
  Dates.removeHours(d: Date) : Date | undefined
 

Compare

import { Compare } from "klingsten-snippets";
   // compares two arrays by attributes, and return an array of errors, if any
  Compare.arrays(arrA: any[], arrB: any[], attr: string[]): CompareError[]  

   // compares two objects by attributes, and return an array of errors, if any
  Compare.objects(objA: any[], objB: any[], attr: string[]): CompareError[]

  // prints the errors
  Compare.printErrors(errors: CompareError[], funcName: string))

Example:

 test_splitNameFromEmail() {
      const test = {
          name: "Strings.splitNameFromEmail()",
          insAndOuts: [
              { in: 'Lars', exp: { name: 'Lars', email: '', isValid: false } },
              { in: '[email protected]', exp: { name: '', email: '[email protected]', isValid: true }
          ]
      }

      let successCount = 0;
      for (let i = 0; i < test.insAndOuts.length; i++) {
          const r = test.insAndOuts[i];
          const result = Strings.splitNameFromEmail(r.in) // test function

          // compare the objects only on attributes 'name' and 'email', disregards rests
          const errors = Compare.objects(result, r.exp, ['name', 'email']);  
          const isSuccess = errors.length === 0;
          if (isSuccess) { successCount++;  }
          else { Compare.printErrors(errors, test.name + ' i=' + i) } 
      }
      console.log("isSuccess", test.insAndOuts.length === successCount, `${test.name} tests=${test.insAndOuts.length} success=${successCount} `);
  }

Timer

import { Timer } from "klingsten-snippets";
  Timer.start('test');                          // starts the time with the name 'test'
  console.log(Timer.stop('test'));              // returns elapsed milliseconds as number
  console.log(Timer.stopAsString('test'));      // returns elapsed milliseconds as as string
  Timer.stopAsLog('test');                      // prints timestamp and elapsed milliseconds to console

Log

import { Log } from "klingsten-snippets";
  Log.log("message")                            // prints timestamp plus message to console.
  Log.now()                                     // returns current time as date as string, like 10:59:59.121
  Log.formatDateToUTCString(date)               // returns date as string, like 10:59:59.121 

Interfaces

interface IUploadFile {
  info: File;     /** javascript File      */
  data: string;   /** Base 64 URL encoded  */
}

source code

https://bitbucket.org/LarsKlingsten/klingsten-snippets-ts