Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More ā†’
Socket
Sign inDemoInstall
Socket

@kluntje/js-utils

Package Overview
Dependencies
Maintainers
0
Versions
22
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@kluntje/js-utils

Collection of js helper functions

  • 0.8.0
  • latest
  • Source
  • npm
  • Socket score

Version published
Maintainers
0
Created
Source

Welcome to @kluntje/js-utils šŸ‘‹

Version License: Apache 2.0

Kluntje/js-utils is a collection of really usefull js functions that can be imported in any project and speed up your daily javascript tasks.

Install

npm install @kuntje/js-utils

Usage

import { inViewport } from '@kluntje/js-utils/lib/dom-helpers';
const inView = inViewport(document.querySelector("#teaser"));

// You can also import from top level. But this is not suitable for three shaking!
import { domHelpers } from "@kluntje/js-utils";
const inView = domHelpers.inViewport(document.querySelector("#teaser"));

Functions

api-helpers

fetchJSON(url, [options]) ā‡’ Promise.<T>

Calls API and returns JSON as Promise

array-helpers

hasElement(array, element) ā‡’ boolean

checks, if element is in given array

isFilledArray(array) ā‡’ boolean

checks, whether given Array exists and has at least one element

mergeArraysBy(array1, array2, checker) ā‡’ Array.<T>

merge two given arrays by the given checker function

pushIfNew(array, newElement) ā‡’ Array.<T>

pushes new Element to given array, if its not already in it

removeItem(array, itemToRemove) ā‡’ Array.<T>

removes specific Item from array and return new array

date-helpers

addDays(date, daysToAdd, [zeroHours]) ā‡’ Date

Adds given amount of days to given date

addLeadingZero(inNumber) ā‡’ string

Optionally Adds leading Zero to Numbers < 10

isEqualDate(dateA, dateB) ā‡’ boolean

Checks whether given dates are equal

sanitizeDateGMTOffset(date) ā‡’ string

Helper to make date parsing cross browser compatible Some browsers (e.g. Safari) need the GMT offset part to be in format "+00:00" This helper makes sure that any present GMT offset follows that format and can safely be parsed: Date.parse("2020-01-01T12:13:14.000+0200") // throws error in Safari Date.parse("2020-01-01T12:13:14.000+02:00") // succes

dom-helpers

addClass(elements, ...classNames)

adds given classes to one or multiple elements

find(parent, selector) ā‡’ Element | null

returns the first child of a specific parent matching the given selector

findAll(parent, selector) ā‡’ Array.<Element>

returns all children of a specific parent matching the given selector

callback(node, index, nodeList)
getCurrentMQ(mediaQueries) ā‡’ string

returns current mediaQuery-name. e.g. "MQ2"

getInnerText(el) ā‡’ string

returns innerText of given Element

getParent(element, parentSelector) ā‡’ Element | null

returns parent of specific class, if found

getUniqueID() ā‡’ string

returns a random String to be used as ID

hasChild(parent, childSelector) ā‡’ boolean

returns if a specific parent has a child matching the given selector

hasClass(element, className) ā‡’ boolean

returns if a specific element has given class

inViewport(element, [parent]) ā‡’ boolean

checks, whether an element is in the viewport

isNodeList(target) ā‡’ boolean

checks, if target is NodeList

onEvent(target, events, handler, context, [options])

adds event with given parameters

removeChildren(parent, selector)

removes all children of a specific parent matching the given selector

removeClass(elements, ...classNames)

removes given class from element

removeEvent(target, events, handler, context, [options])

removes event with given parameters

toggleClass(elements, className, add)

toggles given class on given element

waitFor(timeout) ā‡’ Promise.<void>

resolves Promise after given timeout

waitForAnimationEnd(el, [animationName]) ā‡’ Promise

returns a promise which resolves after the animationend event

waitForEvent(target, eventName, timeout) ā‡’ Promise.<void>

waits for given event for a (optional) max-timeout

waitForInitialization(component) ā‡’ Promise.<void>

Promise that resolves, when the given component is initialized

waitForTransitionEnd(el, [propertyName]) ā‡’ Promise

returns a promise which resolves after the transitionend event

function-helpers

debounce(callback, [wait]) ā‡’ function

returns a debounced function which when called multiple of times each time it waits the waiting duration and if the method was not called during this time, the last call will be passed to the callback.

decoratorGenerator(func) ā‡’ function

generates a decorator factory for the provided helper function. helper function should have this signature: (Function, ...args: any[]) => Function

throttle(callback, [wait]) ā‡’ function

returns a throttled function which when called, waits the given period of time before passing the last call during this time to the provided callback. call .cancel() on the returned function, to cancel the callback invocation.

object-helpers

getValue(obj, path) ā‡’ *

returns nested value without throwing an error if the parent doesn't exist

isEqual(arg1, arg2) ā‡’ boolean

compare two arguments, for object their toString values are compared

isFilledObject(obj) ā‡’ boolean

checks if provided argument is an object which has at least one entry in it.

naiveClone(arg) ā‡’ Nullable.<T> | Array.<T>

returns a deep link of the provided argument

toArray(arg) ā‡’ Array.<T>

returns the argument wrapped in an array if it isn't array itself

toString(arg) ā‡’ string

returns stringified value for the given argument

string-helpers

getCleanString(inputString) ā‡’ string

removes all multi Whitespaces and Newlines in given string

getWordCount(text) ā‡’ number

returns number of words in a given text

removeAllBS(inputString) ā‡’ string

removes all Whitespaces in given string

removeAllNL(inputString) ā‡’ string

removes all Newlines in given string

removeMultiBS(inputString) ā‡’ string

removes multi Whitespaces in given string

toCamelCase(str) ā‡’ string

function to convert texts to camelCase for example ti generate attribute names

toKebabCase(str) ā‡’ string

converts the provided string to a kebab case (kebab-case)

url-helpers

ensureHttpProtocol(url, useHttp) ā‡’ string

Ensures that the given url has an http protocol. If the url does not have an http protocol, it will be prepended with https://. If the url already has an http protocol, it will be returned as is. If the protocol should be http instead of https, you can pass in the optional parameter useHttp as true.

removeHttpProtocol(url) ā‡’ string

returns a string without the http or https protocol

Typedefs

dom-helpers

callback : function

iterates over all nodes in a node list (necessary because IE11 doesn't support .forEach * for NodeLists)

fetchJSON(url, [options]) ā‡’ Promise.<T>

Calls API and returns JSON as Promise

Kind: global function

ParamType
urlstring
[options]RequestInit

Example

// use with async/await
const myApiResponse = await fetchJSON("https://some.api/path")

Example

// use as normal promise
fetchJSON("https://some.api/path").then((data) => console.log("myData:", data));

hasElement(array, element) ā‡’ boolean

checks, if element is in given array

Kind: global function

ParamType
arrayArray.<T>
elementT

Example

const fruits = ["Banana", "Orange", "Apple", "Mango"];

if (hasElement(fruits, "Apple")) {
  console.log("You got an Apple");
}

isFilledArray(array) ā‡’ boolean

checks, whether given Array exists and has at least one element

Kind: global function

ParamType
arrayArray.<T>

Example

const myBooks = await fetchJSON("https://my-book-store.api/books");
if (isFilledArray(myBooks)) {
  console.log(`${myBooks.length} Books found!`)
} else {
  console.log("Sorry, no Books found");
}

mergeArraysBy(array1, array2, checker) ā‡’ Array.<T>

merge two given arrays by the given checker function

Kind: global function

ParamTypeDescription
array1Array.<T>
array2Array.<T>
checkerfunction

if this function returns true for a specific element combination the elements are getting merged

Example

const defaultUsers = [
  {
    name: "Admin",
    mail: "admin@company.com"
  },
  {
    name: "CI",
    mail: "ci@company.com"
  }
];

const projectUsers = [
  {
    name: "Admin",
    mail: "admin@company.com"
  },
  {
    name: "User1",
    mail: "user-one@company.com"
  },
  {
    name: "User2",
    mail: "user-two@company.com"
  }
];

const userList = mergeArraysBy(defaultUsers, projectUsers, (defaultUser, array) => {
  return !array.some((projectUser) => projectUser.mail === defaultUser.mail)
})

// userList
// [
//   {
//     "name": "CI",
//     "mail": "ci@company.com"
//   },
//   {
//     "name": "Admin",
//     "mail": "admin@company.com"
//   },
//   {
//     "name": "User1",
//     "mail": "user-one@company.com"
//   },
//   {
//     "name": "User2",
//     "mail": "user-two@company.com"
//   }
// ] 

pushIfNew(array, newElement) ā‡’ Array.<T>

pushes new Element to given array, if its not already in it

Kind: global function

ParamType
arrayArray.<T>
newElementT

Example

const fruitStore = ["Banana", "Orange", "Apple", "Mango"];
const newFruit = getInputValue(...)
const newFruitStore = pushIfNew(fruitStore, newFruit);

removeItem(array, itemToRemove) ā‡’ Array.<T>

removes specific Item from array and return new array

Kind: global function

ParamType
arrayArray.<T>
itemToRemoveT

Example

const fruitStore = ["Banana", "Orange", "Apple", "Mango"];
const newFruitStore = removeItem(fruitStore, "Apple"); // ["Banana", "Orange", "Mango"]

addDays(date, daysToAdd, [zeroHours]) ā‡’ Date

Adds given amount of days to given date

Kind: global function

ParamTypeDefaultDescription
dateDate
daysToAddnumber
[zeroHours]booleanfalse

set time to 0:00:00

Example

const today = new Date();
const tomorrow = addDays(today, 2);

addLeadingZero(inNumber) ā‡’ string

Optionally Adds leading Zero to Numbers < 10

Kind: global function

ParamType
inNumbernumber

Example

const today = new Date();
const formattedDateSting = `${addLeadingZero(today.getDate())}.${addLeadingZero(today.getMonth() + 1)}.${today.getFullYear()}`;

isEqualDate(dateA, dateB) ā‡’ boolean

Checks whether given dates are equal

Kind: global function

ParamType
dateADate
dateBDate

Example

const dateA = new Date(2020, 1, 29, 22, 30);
const dateB = new Date(2020, 1, 29, 18, 20);
isEqualDate(dateA. dateB); // true

sanitizeDateGMTOffset(date) ā‡’ string

Helper to make date parsing cross browser compatible Some browsers (e.g. Safari) need the GMT offset part to be in format "+00:00" This helper makes sure that any present GMT offset follows that format and can safely be parsed: Date.parse("2020-01-01T12:13:14.000+0200") // throws error in Safari Date.parse("2020-01-01T12:13:14.000+02:00") // succes

Kind: global function
Returns: string -

correctly formatted date

ParamTypeDescription
datestring

date string to be sanitized for parsing

Example

sanitizeDateGMTOffset("2020-01-01T12:13:14.000+0200") // "2020-01-01T12:13:14.000+02:00"

addClass(elements, ...classNames)

adds given classes to one or multiple elements

Kind: global function

ParamType
elementsElement | Iterable.<Element> | NodeListOf.<Element> | null
...classNamesstring

Example

const button = document.querySelector('.button');
addClass(button, 'my-button');

Example

const inputs = document.querySelectorAll('input');
addClass(inputs, 'my-button');

find(parent, selector) ā‡’ Element | null

returns the first child of a specific parent matching the given selector

Kind: global function

ParamType
parentElement | Document | null
selectorstring

Example

const input = find(document, 'input');

findAll(parent, selector) ā‡’ Array.<Element>

returns all children of a specific parent matching the given selector

Kind: global function

ParamType
parentElement | Document | null
selectorstring

Example

const inputs = findAll(document, 'input');

callback(node, index, nodeList)

Kind: global function

ParamType
nodeNode
indexNumber
nodeListNodeListOf.<T>

getCurrentMQ(mediaQueries) ā‡’ string

returns current mediaQuery-name. e.g. "MQ2"

Kind: global function
Returns: string -

  • mediaQuery name e.g. MQ1
ParamType
mediaQueriesArray.<MQDefinition>

Example

const myMqs = [
  {
    name: 'MQ2',
    query: '(min-width: 769px)'
  },
  {
    name: 'MQ1',
    query: '(min-width: 0px)'
  }
];

const curMQ = getCurrentMQ(myMqs);

getInnerText(el) ā‡’ string

returns innerText of given Element

Kind: global function

ParamType
elHTMLElement

Example

const myArticle = document.querySelector('article');
const articleText = getInnerText(myArticle);

getParent(element, parentSelector) ā‡’ Element | null

returns parent of specific class, if found

Kind: global function

ParamType
elementElement
parentSelectorstring

Example

const myText = document.querySelector('p');
const myArticle = getParent(myText, 'article');

getUniqueID() ā‡’ string

returns a random String to be used as ID

Kind: global function

hasChild(parent, childSelector) ā‡’ boolean

returns if a specific parent has a child matching the given selector

Kind: global function

ParamType
parentElement
childSelectorstring

Example

const article = document.querySelector('article');
if (hasChild(article, '.cta')) console.log('please click');

hasClass(element, className) ā‡’ boolean

returns if a specific element has given class

Kind: global function

ParamType
elementElement
classNamestring

Example

const cta = document.querySelector('button');
if (hasClass(cta, 'primary')) console.log("primary")

inViewport(element, [parent]) ā‡’ boolean

checks, whether an element is in the viewport

Kind: global function

ParamType
elementElement
[parent]Element

Example

const image = document.querySelector('image');
if (inViewport(image)) image.setAttribute('src', image.dataset('src'));

isNodeList(target) ā‡’ boolean

checks, if target is NodeList

Kind: global function

ParamType
targetany

onEvent(target, events, handler, context, [options])

adds event with given parameters

Kind: global function

ParamType
targetEventTarget | null
eventsstring | Array.<string>
handlerfunction
contextContext
[options]AddEventListenerOptions

Example

const buttons = findAll(document, 'button);
onEvent(buttons, 'click', () => console.log('button clicked'), this);

removeChildren(parent, selector)

removes all children of a specific parent matching the given selector

Kind: global function

ParamType
parentElement
selectorstring

Example

const article = find('article);
removeChildren(article, '.ad');

removeClass(elements, ...classNames)

removes given class from element

Kind: global function

ParamType
elementsElement | Iterable.<Element> | NodeListOf.<Element> | null
...classNamesstring

Example

const button = document.querySelector('.button');
removeClass(button, 'active');

Example

const inputs = document.querySelectorAll('input');
removeClass(inputs, 'active');

removeEvent(target, events, handler, context, [options])

removes event with given parameters

Kind: global function

ParamType
targetHTMLElement | Iterable.<HTMLElement>
eventsstring | Array.<string>
handlerfunction
contextContext
[options]AddEventListenerOptions

Example

const buttons = findAll(document, 'button);
removeEvent(buttons, 'click', () => console.log('button clicked'), this);

toggleClass(elements, className, add)

toggles given class on given element

Kind: global function

ParamType
elementsElement | Iterable.<Element> | NodeListOf.<Element> | null
classNamestring
addboolean

Example

const button = find(document, 'button');
onEvent(button, 'click', () => toggleClass(button, 'active'), this);

waitFor(timeout) ā‡’ Promise.<void>

resolves Promise after given timeout

Kind: global function

ParamTypeDescription
timeoutnumber

timeout in milliseconds

Example

addClass(button, 'animate');
waitFor(300).then(() => removeClass(button, 'animate'));

Example

addClass(button, 'animate');
await waitFor(300);
removeClass(button, 'animate');

waitForAnimationEnd(el, [animationName]) ā‡’ Promise

returns a promise which resolves after the animationend event

Kind: global function

ParamTypeDescription
elHTMLElement | SVGElement

DOM Element which has the css animation

[animationName]string

keyframes' name. e.g. "slideOut"

Example

  el.classList.add("hide");
  await waitForAnimationEnd(el, "fade-out");
  el.parentElement.removeChild(el);
  // css:
  // .hide {
  //   animation: fade-out 0.5s forwards;
  // }

waitForEvent(target, eventName, timeout) ā‡’ Promise.<void>

waits for given event for a (optional) max-timeout

Kind: global function

ParamTypeDescription
targetEventTarget
eventNamestring
timeoutnumber

timeout in milliseconds

Example

addClass(button, 'animate');
waitForEvent(button, 'transitionend', 500).then(() => removeClass(button, 'animate'));

Example

addClass(button, 'animate');
await waitForEvent(button, 'transitionend', 500);
removeClass(button, 'animate');

waitForInitialization(component) ā‡’ Promise.<void>

Promise that resolves, when the given component is initialized

Kind: global function

ParamType
componentComponent

Example

waitForInitialization(my-input).then(() => my-input.value = 'Hello World');

Example

await  waitForInitialization(my-input);
my-input.value = 'Hello World';

waitForTransitionEnd(el, [propertyName]) ā‡’ Promise

returns a promise which resolves after the transitionend event

Kind: global function

ParamTypeDescription
elHTMLElement | SVGElement

DOM Element which has the css transition

[propertyName]string

transition's propertyName. e.g. "width"

Example

  menu.classList.add("open");
  await waitForTransitionEnd(menu, "transform");
  input.classList.add("visible");
  await waitForTransitionEnd(input, "opacity");
  input.focus();

debounce(callback, [wait]) ā‡’ function

returns a debounced function which when called multiple of times each time it waits the waiting duration and if the method was not called during this time, the last call will be passed to the callback.

Kind: global function
Debounce(100): scrollHandler(event) { // ... } }

ParamTypeDefaultDescription
callbackfunction

function to be called after the last wait period

[wait]number0

waiting period in ms before the callback is invoked if during this time the debounced method was not called

Example

const debounced = debounce(console.log, 500);
  debonced("Hi");
  debonced("Hello");
  debonced("Hey");
  if (neverMind) debonced.cancel();
  // logs only "Hey", and when `neverMind === false`, doesn't log anything.


  // or instead of decorator on class methods
  Class Component {
    constructor() {
      window.addEventListener("resize", this.resizeHandler);
      window.addEventListener("scroll", this.scrollHandler);
    }

    resizeHandler = debounce(event => {
      // event handlers logic
    }, 100);

    // or when the decorator is imported:
    

decoratorGenerator(func) ā‡’ function

generates a decorator factory for the provided helper function. helper function should have this signature: (Function, ...args: any[]) => Function

Kind: global function

ParamTypeDescription
funcfunction

function to be wrapped with a decorator factory

throttle(callback, [wait]) ā‡’ function

returns a throttled function which when called, waits the given period of time before passing the last call during this time to the provided callback. call .cancel() on the returned function, to cancel the callback invocation.

Kind: global function

ParamTypeDefaultDescription
callbackfunction

function to be caled after the last wait period

[wait]number0

waiting period in ms before the callback is invoked if during this time the debounced method was not called

Example

window.addEventListener("resize", throttle(updateSlider, 100));

getValue(obj, path) ā‡’ *

Deprecated

returns nested value without throwing an error if the parent doesn't exist

Kind: global function
Returns: * -

  • returned the found value or undefined
ParamTypeDescription
objObject

object to be looked for value

pathstring

a string with dot separated levels: e.g "a.b"

Example

const obj = {
  a: {
    b: {
      c: 1
    },
    d: true
  }
};
getValue(obj, "a.b") === {c: 1};
getValue(obj, "a.f") === undefined;

isEqual(arg1, arg2) ā‡’ boolean

compare two arguments, for object their toString values are compared

Kind: global function

ParamType
arg1T
arg2T

Example

if (!isEqual(oldState, newState)) console.log('state changed');

isFilledObject(obj) ā‡’ boolean

checks if provided argument is an object which has at least one entry in it.

Kind: global function

ParamType
objany

Example

isFilledObject({ k: "v" }) === true;
isFilledObject({}) === false;
isFilledObject("text") === false;

naiveClone(arg) ā‡’ Nullable.<T> | Array.<T>

returns a deep link of the provided argument

Kind: global function

ParamType
argNullable.<T> | Array.<T>

Example

const state = naiveClone(initialState);

toArray(arg) ā‡’ Array.<T>

returns the argument wrapped in an array if it isn't array itself

Kind: global function

ParamType
argT | Array.<T>

Example

const apple = "Apple";
const fruits = toArray(apple); // ["Apple"] 

toString(arg) ā‡’ string

returns stringified value for the given argument

Kind: global function

ParamType
arg*

Example

const submitData = toString(formData);

getCleanString(inputString) ā‡’ string

removes all multi Whitespaces and Newlines in given string

Kind: global function

ParamType
inputStringstring

Example

const article = find(document, 'aricle');
const text = getCleanString(article.innerText);

getWordCount(text) ā‡’ number

returns number of words in a given text

Kind: global function

ParamType
textstring

Example

const article = find(document, 'aricle');
const articleWords = getWordCount(article.innerText);

removeAllBS(inputString) ā‡’ string

removes all Whitespaces in given string

Kind: global function

ParamType
inputStringstring

Example

removeAllBS('Hello My  World  '); // HelloMyWorld

removeAllNL(inputString) ā‡’ string

removes all Newlines in given string

Kind: global function

ParamType
inputStringstring

Example

const article = find(document, 'aricle');
const textString = removeAllNL(article.innerText);

removeMultiBS(inputString) ā‡’ string

removes multi Whitespaces in given string

Kind: global function

ParamType
inputStringstring

Example

removeMultiBS('Hello My      World'); // Hello My World

toCamelCase(str) ā‡’ string

function to convert texts to camelCase for example ti generate attribute names

Kind: global function

ParamTypeDescription
strstring

sequence of letters, dashes and spaces to be converted to camelCase

Example

toCamelCase("some-text") === "someText";
toCamelCase("some other text") === "someOtherText";

toKebabCase(str) ā‡’ string

converts the provided string to a kebab case (kebab-case)

Kind: global function

ParamType
strstring

Example

toKebabCase("keyValuePair") === "key-value-pair"

ensureHttpProtocol(url, useHttp) ā‡’ string

Ensures that the given url has an http protocol. If the url does not have an http protocol, it will be prepended with https://. If the url already has an http protocol, it will be returned as is. If the protocol should be http instead of https, you can pass in the optional parameter useHttp as true.

Kind: global function

ParamTypeDefault
urlstring
useHttpbooleanfalse

Example

const url = 'https://www.google.com';
const result = ensureHttpProtocol(url);
console.log(result);
// => 'https://www.google.com'

const url = 'www.google.com';
const result = ensureHttpProtocol(url);
console.log(result);
// => 'https://www.google.com'

const url = 'http://www.google.com';
const result = ensureHttpProtocol(url);
console.log(result);
// => 'http://www.google.com'

removeHttpProtocol(url) ā‡’ string

returns a string without the http or https protocol

Kind: global function

ParamType
urlstring

Example

const url = 'https://www.google.com';
const result = removeHttpProtocol(url);
console.log(result);
// => 'www.google.com'

callback : function

iterates over all nodes in a node list (necessary because IE11 doesn't support .forEach * for NodeLists)

Kind: global typedef

ParamTypeDefault
nodeListNodeListOf.<T>
[context]anywindow

Example

const buttons = document.querySelectorAll('button');
forEachNode(buttons, (button, idx) => addClass(button, `my-button--${idx}`))

Author

šŸ‘¤ Frederik Riewerts frederik.riewerts@gmail.com

Show your support

Give a ā­ļø if this project helped you!


This README was generated with ā¤ļø by readme-md-generator

FAQs

Package last updated on 05 Dec 2024

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with āš”ļø by Socket Inc