@kluntje/js-utils
v0.7.3
Published
Collection of js helper functions
Downloads
6,071
Readme
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
| Param | Type | | --- | --- | | url | string | | [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
Kind: global function
| Param | Type | | --- | --- | | array | Array.<T> | | element | T |
Example
const fruits = ["Banana", "Orange", "Apple", "Mango"];
if (hasElement(fruits, "Apple")) {
console.log("You got an Apple");
}
isFilledArray(array) ⇒ boolean
Kind: global function
| Param | Type | | --- | --- | | array | Array.<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
| Param | Type | Description | | --- | --- | --- | | array1 | Array.<T> | | | array2 | Array.<T> | | | checker | function | if this function returns true for a specific element combination the elements are getting merged |
Example
const defaultUsers = [
{
name: "Admin",
mail: "[email protected]"
},
{
name: "CI",
mail: "[email protected]"
}
];
const projectUsers = [
{
name: "Admin",
mail: "[email protected]"
},
{
name: "User1",
mail: "[email protected]"
},
{
name: "User2",
mail: "[email protected]"
}
];
const userList = mergeArraysBy(defaultUsers, projectUsers, (defaultUser, array) => {
return !array.some((projectUser) => projectUser.mail === defaultUser.mail)
})
// userList
// [
// {
// "name": "CI",
// "mail": "[email protected]"
// },
// {
// "name": "Admin",
// "mail": "[email protected]"
// },
// {
// "name": "User1",
// "mail": "[email protected]"
// },
// {
// "name": "User2",
// "mail": "[email protected]"
// }
// ]
pushIfNew(array, newElement) ⇒ Array.<T>
Kind: global function
| Param | Type | | --- | --- | | array | Array.<T> | | newElement | T |
Example
const fruitStore = ["Banana", "Orange", "Apple", "Mango"];
const newFruit = getInputValue(...)
const newFruitStore = pushIfNew(fruitStore, newFruit);
removeItem(array, itemToRemove) ⇒ Array.<T>
Kind: global function
| Param | Type | | --- | --- | | array | Array.<T> | | itemToRemove | T |
Example
const fruitStore = ["Banana", "Orange", "Apple", "Mango"];
const newFruitStore = removeItem(fruitStore, "Apple"); // ["Banana", "Orange", "Mango"]
addDays(date, daysToAdd, [zeroHours]) ⇒ Date
Kind: global function
| Param | Type | Default | Description | | --- | --- | --- | --- | | date | Date | | | | daysToAdd | number | | | | [zeroHours] | boolean | false | set time to 0:00:00 |
Example
const today = new Date();
const tomorrow = addDays(today, 2);
addLeadingZero(inNumber) ⇒ string
Kind: global function
| Param | Type | | --- | --- | | inNumber | number |
Example
const today = new Date();
const formattedDateSting = `${addLeadingZero(today.getDate())}.${addLeadingZero(today.getMonth() + 1)}.${today.getFullYear()}`;
isEqualDate(dateA, dateB) ⇒ boolean
Kind: global function
| Param | Type | | --- | --- | | dateA | Date | | dateB | Date |
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
| Param | Type | Description | | --- | --- | --- | | date | string | 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)
Kind: global function
| Param | Type | | --- | --- | | elements | Element | Iterable.<Element> | NodeListOf.<Element> | null | | ...classNames | string |
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
| Param | Type | | --- | --- | | parent | Element | Document | null | | selector | string |
Example
const input = find(document, 'input');
findAll(parent, selector) ⇒ Array.<Element>
Kind: global function
| Param | Type | | --- | --- | | parent | Element | Document | null | | selector | string |
Example
const inputs = findAll(document, 'input');
callback(node, index, nodeList)
Kind: global function
| Param | Type | | --- | --- | | node | Node | | index | Number | | nodeList | NodeListOf.<T> |
getCurrentMQ(mediaQueries) ⇒ string
Kind: global function
Returns: string -
| Param | Type | | --- | --- | | mediaQueries | Array.<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
| Param | Type | | --- | --- | | el | HTMLElement |
Example
const myArticle = document.querySelector('article');
const articleText = getInnerText(myArticle);
getParent(element, parentSelector) ⇒ Element | null
Kind: global function
| Param | Type | | --- | --- | | element | Element | | parentSelector | string |
Example
const myText = document.querySelector('p');
const myArticle = getParent(myText, 'article');
getUniqueID() ⇒ string
Kind: global function
hasChild(parent, childSelector) ⇒ boolean
Kind: global function
| Param | Type | | --- | --- | | parent | Element | | childSelector | string |
Example
const article = document.querySelector('article');
if (hasChild(article, '.cta')) console.log('please click');
hasClass(element, className) ⇒ boolean
Kind: global function
| Param | Type | | --- | --- | | element | Element | | className | string |
Example
const cta = document.querySelector('button');
if (hasClass(cta, 'primary')) console.log("primary")
inViewport(element, [parent]) ⇒ boolean
Kind: global function
| Param | Type | | --- | --- | | element | Element | | [parent] | Element |
Example
const image = document.querySelector('image');
if (inViewport(image)) image.setAttribute('src', image.dataset('src'));
isNodeList(target) ⇒ boolean
Kind: global function
| Param | Type | | --- | --- | | target | any |
onEvent(target, events, handler, context, [options])
Kind: global function
| Param | Type | | --- | --- | | target | EventTarget | null | | events | string | Array.<string> | | handler | function | | context | Context | | [options] | AddEventListenerOptions |
Example
const buttons = findAll(document, 'button);
onEvent(buttons, 'click', () => console.log('button clicked'), this);
removeChildren(parent, selector)
Kind: global function
| Param | Type | | --- | --- | | parent | Element | | selector | string |
Example
const article = find('article);
removeChildren(article, '.ad');
removeClass(elements, ...classNames)
Kind: global function
| Param | Type | | --- | --- | | elements | Element | Iterable.<Element> | NodeListOf.<Element> | null | | ...classNames | string |
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
| Param | Type | | --- | --- | | target | HTMLElement | Iterable.<HTMLElement> | | events | string | Array.<string> | | handler | function | | context | Context | | [options] | AddEventListenerOptions |
Example
const buttons = findAll(document, 'button);
removeEvent(buttons, 'click', () => console.log('button clicked'), this);
toggleClass(elements, className, add)
Kind: global function
| Param | Type | | --- | --- | | elements | Element | Iterable.<Element> | NodeListOf.<Element> | null | | className | string | | add | boolean |
Example
const button = find(document, 'button');
onEvent(button, 'click', () => toggleClass(button, 'active'), this);
waitFor(timeout) ⇒ Promise.<void>
Kind: global function
| Param | Type | Description | | --- | --- | --- | | timeout | number | 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
Kind: global function
| Param | Type | Description | | --- | --- | --- | | el | HTMLElement | 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>
Kind: global function
| Param | Type | Description | | --- | --- | --- | | target | EventTarget | | | eventName | string | | | timeout | number | 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>
Kind: global function
| Param | Type | | --- | --- | | component | Component |
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
| Param | Type | Description | | --- | --- | --- | | el | HTMLElement | 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
Kind: global function
Debounce(100): scrollHandler(event) {
// ...
}
}
| Param | Type | Default | Description | | --- | --- | --- | --- | | callback | function | | function to be called after the last wait period | | [wait] | number | 0 | 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
Kind: global function
| Param | Type | Description | | --- | --- | --- | | func | function | function to be wrapped with a decorator factory |
throttle(callback, [wait]) ⇒ function
Kind: global function
| Param | Type | Default | Description | | --- | --- | --- | --- | | callback | function | | function to be caled after the last wait period | | [wait] | number | 0 | 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
Kind: global function
Returns: * -
| Param | Type | Description | | --- | --- | --- | | obj | Object | object to be looked for value | | path | string | 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
Kind: global function
| Param | Type | | --- | --- | | arg1 | T | | arg2 | T |
Example
if (!isEqual(oldState, newState)) console.log('state changed');
isFilledObject(obj) ⇒ boolean
Kind: global function
| Param | Type | | --- | --- | | obj | any |
Example
isFilledObject({ k: "v" }) === true;
isFilledObject({}) === false;
isFilledObject("text") === false;
naiveClone(arg) ⇒ Nullable.<T> | Array.<T>
Kind: global function
| Param | Type | | --- | --- | | arg | Nullable.<T> | Array.<T> |
Example
const state = naiveClone(initialState);
toArray(arg) ⇒ Array.<T>
Kind: global function
| Param | Type | | --- | --- | | arg | T | Array.<T> |
Example
const apple = "Apple";
const fruits = toArray(apple); // ["Apple"]
toString(arg) ⇒ string
Kind: global function
| Param | Type | | --- | --- | | arg | * |
Example
const submitData = toString(formData);
getCleanString(inputString) ⇒ string
Kind: global function
| Param | Type | | --- | --- | | inputString | string |
Example
const article = find(document, 'aricle');
const text = getCleanString(article.innerText);
getWordCount(text) ⇒ number
Kind: global function
| Param | Type | | --- | --- | | text | string |
Example
const article = find(document, 'aricle');
const articleWords = getWordCount(article.innerText);
removeAllBS(inputString) ⇒ string
Kind: global function
| Param | Type | | --- | --- | | inputString | string |
Example
removeAllBS('Hello My World '); // HelloMyWorld
removeAllNL(inputString) ⇒ string
Kind: global function
| Param | Type | | --- | --- | | inputString | string |
Example
const article = find(document, 'aricle');
const textString = removeAllNL(article.innerText);
removeMultiBS(inputString) ⇒ string
Kind: global function
| Param | Type | | --- | --- | | inputString | string |
Example
removeMultiBS('Hello My World'); // Hello My World
toCamelCase(str) ⇒ string
Kind: global function
| Param | Type | Description | | --- | --- | --- | | str | string | sequence 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
| Param | Type | | --- | --- | | str | string |
Example
toKebabCase("keyValuePair") === "key-value-pair"
ensureHttpProtocol(url, useHttp) ⇒ string
Kind: global function
| Param | Type | Default | | --- | --- | --- | | url | string | | | useHttp | boolean | false |
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
| Param | Type | | --- | --- | | url | string |
Example
const url = 'https://www.google.com';
const result = removeHttpProtocol(url);
console.log(result);
// => 'www.google.com'
callback : function
Kind: global typedef
| Param | Type | Default | | --- | --- | --- | | nodeList | NodeListOf.<T> | | | [context] | any | window |
Example
const buttons = document.querySelectorAll('button');
forEachNode(buttons, (button, idx) => addClass(button, `my-button--${idx}`))
Author
👤 Frederik Riewerts [email protected]
Show your support
Give a ⭐️ if this project helped you!
This README was generated with ❤️ by readme-md-generator