0.7.3 • Published 4 months ago

@kluntje/js-utils v0.7.3

Weekly downloads
24
License
Apache-2.0
Repository
github
Last release
4 months ago

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

array-helpers

date-helpers

dom-helpers

function-helpers

object-helpers

string-helpers

url-helpers

Typedefs

dom-helpers

fetchJSON(url, options) ⇒ Promise.<T>

Kind: global function

ParamType
urlstring
optionsRequestInit

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

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

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>

Kind: global function

ParamTypeDescription
array1Array.<T>
array2Array.<T>
checkerfunctionif 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>

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>

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

Kind: global function

ParamTypeDefaultDescription
dateDate
daysToAddnumber
zeroHoursbooleanfalseset time to 0:00:00

Example

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

addLeadingZero(inNumber) ⇒ string

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

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

Kind: global function
Returns: string - correctly formatted date

ParamTypeDescription
datestringdate 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)

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

Kind: global function

ParamType
parentElement | Document | null
selectorstring

Example

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

findAll(parent, selector) ⇒ Array.<Element>

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

Kind: global function
Returns: string -

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

Kind: global function

ParamType
elHTMLElement

Example

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

getParent(element, parentSelector) ⇒ Element | null

Kind: global function

ParamType
elementElement
parentSelectorstring

Example

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

getUniqueID() ⇒ string

Kind: global function

hasChild(parent, childSelector) ⇒ boolean

Kind: global function

ParamType
parentElement
childSelectorstring

Example

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

hasClass(element, className) ⇒ boolean

Kind: global function

ParamType
elementElement
classNamestring

Example

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

inViewport(element, parent) ⇒ boolean

Kind: global function

ParamType
elementElement
parentElement

Example

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

isNodeList(target) ⇒ boolean

Kind: global function

ParamType
targetany

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

Kind: global function

ParamType
targetEventTarget | null
eventsstring | Array.<string>
handlerfunction
contextContext
optionsAddEventListenerOptions

Example

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

removeChildren(parent, selector)

Kind: global function

ParamType
parentElement
selectorstring

Example

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

removeClass(elements, ...classNames)

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)

Kind: global function

ParamType
targetHTMLElement | Iterable.<HTMLElement>
eventsstring | Array.<string>
handlerfunction
contextContext
optionsAddEventListenerOptions

Example

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

toggleClass(elements, className, add)

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>

Kind: global function

ParamTypeDescription
timeoutnumbertimeout 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

Kind: global function

ParamTypeDescription
elHTMLElement | SVGElementDOM Element which has the css animation
animationNamestringkeyframes' 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>

Kind: global function

ParamTypeDescription
targetEventTarget
eventNamestring
timeoutnumbertimeout 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>

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

Kind: global function

ParamTypeDescription
elHTMLElement | SVGElementDOM Element which has the css transition
propertyNamestringtransition'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

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

ParamTypeDefaultDescription
callbackfunctionfunction to be called after the last wait period
waitnumber0waiting 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

Kind: global function

ParamTypeDescription
funcfunctionfunction to be wrapped with a decorator factory

throttle(callback, wait) ⇒ function

Kind: global function

ParamTypeDefaultDescription
callbackfunctionfunction to be caled after the last wait period
waitnumber0waiting 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

Kind: global function
Returns: * -

ParamTypeDescription
objObjectobject to be looked for value
pathstringa 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

Kind: global function

ParamType
arg1T
arg2T

Example

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

isFilledObject(obj) ⇒ boolean

Kind: global function

ParamType
objany

Example

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

naiveClone(arg) ⇒ Nullable.<T> | Array.<T>

Kind: global function

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

Example

const state = naiveClone(initialState);

toArray(arg) ⇒ Array.<T>

Kind: global function

ParamType
argT | Array.<T>

Example

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

toString(arg) ⇒ string

Kind: global function

ParamType
arg*

Example

const submitData = toString(formData);

getCleanString(inputString) ⇒ string

Kind: global function

ParamType
inputStringstring

Example

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

getWordCount(text) ⇒ number

Kind: global function

ParamType
textstring

Example

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

removeAllBS(inputString) ⇒ string

Kind: global function

ParamType
inputStringstring

Example

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

removeAllNL(inputString) ⇒ string

Kind: global function

ParamType
inputStringstring

Example

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

removeMultiBS(inputString) ⇒ string

Kind: global function

ParamType
inputStringstring

Example

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

toCamelCase(str) ⇒ string

Kind: global function

ParamTypeDescription
strstringsequence of letters, dashes and spaces to be converted to camelCase

Example

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

toKebabCase(str) ⇒ string

Kind: global function

ParamType
strstring

Example

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

ensureHttpProtocol(url, useHttp) ⇒ string

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

Kind: global function

ParamType
urlstring

Example

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

callback : function

Kind: global typedef

ParamTypeDefault
nodeListNodeListOf.<T>
contextanywindow

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

0.7.3

4 months ago

0.7.2

1 year ago

0.7.1-alpha.9

2 years ago

0.7.1-alpha.5

2 years ago

0.7.1-alpha.7

2 years ago

0.7.1-alpha.1

2 years ago

0.7.1-alpha.10

2 years ago

0.7.1-alpha.3

2 years ago

0.7.1-alpha.0

2 years ago

0.7.1

2 years ago

0.7.0

2 years ago

0.6.0

2 years ago

0.5.1-alpha.2

3 years ago

0.4.1-alpha.4

3 years ago

0.5.0

3 years ago

0.4.0

4 years ago

0.3.1-alpha.5

4 years ago

0.3.1-alpha.3

4 years ago

0.3.0

4 years ago

0.2.0

4 years ago

0.1.0

4 years ago