klingsten-snippets
TypeScript icon, indicating that this package has built-in type declarations

1.0.51 • Public • Published

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" <l@email.dk>; lars@email.com, Bob, Lin <sn@g.com> ';
 // note ',' or ';' between quotes (""), and delimtors ',' and ';'
 
 const nameEmailArr :  = Strings.splitNameFromEmail( emailStr );
  // in:  emailStr // see above 
  // out: 
  [ { name: "lars, K", email: "l@email.dk" },
    { name: "",        email: "lars@email.com"  },
    { name: "Bob, Lin",email: "sn@g.com"  }
  ]  // 3 items
  
 const email0 = Strings.splitNameFromEmail(strArr[0]);   
 // in:  strArr[0] = '"lars, K" <l@email.dk>'
 // out: email0 = {name:'lars, K', email:'l@email.dk' }
   
 const email1 = Strings.splitNameFromEmail(strArr[1]);   
 // in:  strArr[1] = 'lars@email.com'
 // out: email1 = {name:'', email:'lars@email.dk' }

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: 'lars@EMAIL.com', exp: { name: '', email: 'lars@email.com', 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

Readme

Keywords

none

Package Sidebar

Install

npm i klingsten-snippets

Weekly Downloads

1,855

Version

1.0.51

License

ISC

Unpacked Size

73 kB

Total Files

42

Last publish

Collaborators

  • larsk