services
Assorted JavaScript services.
Installation
npm
Via $ npm install -S @haensl/services
yarn
Via $ yarn add @haensl/services
Usage
-
Use services in your code:
import { platform } from '@haensl/services';
if (platform.hasWindow) {
// code that relies on existance
// of a global window object
}
Available services
- component: Wraps utility functions useful in a component context, e.g. generate stateful class names.
- numbers: Wraps utility functions pertaining to numbers, e.g. generating random numbers.
- platform: Wraps information about the platform, e.g. is there a
window
? what is the current scroll position? is there local storage? etc. - throttle: Wraps functionality to throttle function execution, e.g.
debounce
.
component service
The component service wraps utility functions useful when working with components.
Methods
Methods
'--'
])
className(states, basename, [separator = Returns a class list string composed of the basename
followed by the basename
concatenated with any truthy properties in states
, wherein the concatenation is separated by separator
(default: two dashes, --
).
Example
import React, { useState } from 'react';
import { component } from '@haensl/services';
const MyComponent = () => {
const [isDoingStuff, setIsDoingStuff] = useState(false);
// code manipulating isDoingStuff
const cn = component.className({
isDoingStuff
}, 'MyComponent');
// if isDoingStuff is true
// cn === "MyComponent MyComponent--isDoingStuff"
// else
// cn === "MyComponent"
return (
<div className={ cn }> // className="MyComponent MyComponent--isDoingStuff"
// ...
</div>
);
};
setInputValue(input, value)
Sets the value
of an HTMLInputElement and triggers an 'input'
event. This is for example useful in cases where frameworks' event management makes it hard to programmatically trigger events that adhere to the native JavaScript event behaviour.
Example
import React, { useEffect, useRef, useState } from 'react';
import { component } from '@haensl/services';
const MyComponent = ({
defaultValue = '',
onChange
}) => {
const [value, setValue] = useState(defaultValue);
const input = useRef();
useEffect(() => {
if (!input.current) {
return;
}
component.setInputValue(input.current, defaultValue);
}, [defaultValue]);
return (
<div>
// ...
<input
ref={ input }
onChange={ onChange }
value={ value }
/>
</div>
);
};
numbers service
The numbers service wraps utility functions pertaining to numbers, e.g. random number generation.
Methods
Methods
rand({ min = 0, max = 1 })
Returns a random floating point number between min (inclusive) and max (exclusive). Due to JavaScript rounding, the value will never equal max
.
Example
import { numbers } from '@haensl/services';
// generates a random number between 0 (inclusive) and 1 (exclusive)
const n = numbers.rand();
// generates a random number between 1 (inclusive) and 300 (exclusive)
const k = numbers.rand({ min: 1, max: 300});
randInt({ min, max })
Returns a random integer number between min and max (inclusive).
Example
import { numbers } from '@haensl/services';
// generates a random number between 0 (inclusive) and 3 (inclusive)
const n = numbers.randInt({ min: 0, max: 3 });
platform service
The platform service wraps information about the current runtime platform, e.g. is there a window
? what is the current scroll position? is there local storage? etc.
Properties
Methods
Properties
hasDocument
Boolean, indicating whether or not the current runtime provides a global document
object.
Example
import { platform } from '@haensl/services';
if (platform.hasDocument) {
// code that relies on global document object,
// e.g.
if (/utf-8/i.test(document.characterSet)) {
// do stuff that requires utf-8 encoding
}
}
hasDocumentElement
Boolean, indicating whether or not the current runtime provides a global document.documentElement
object.
Example
import { platform } from '@haensl/services';
if (platform.hasDocumentElement) {
// code that relies on the existence of document.documentElement,
// e.g.
if (!(document.documentElement instanceof HTMLHtmlElement)) {
// do stuff the XML way, because we're not in an HTML document
}
}
hasLocalStorage
Boolean, indicating whether or not the current runtime provides a global window.localStorage
object.
Example
import { platform } from '@haensl/services';
if (platform.hasLocalStorage) {
// code that relies on local storage,
// e.g.
window.localStorage.setItem('my-data', data);
} else {
// code that saves data elsewhere
}
hasSessionStorage
Boolean, indicating whether or not the current runtime provides a global window.sessionStorage
object.
Example
import { platform } from '@haensl/services';
if (platform.hasSessionStorage) {
// code that relies on session storage,
// e.g.
window.sessionStorage.setItem('my-data', data);
} else {
// code that saves data elsewhere
}
hasWindow
Boolean, indicating whether or not the current runtime provides a global window
object.
Example
import { platform } from '@haensl/services';
if (platform.hasWindow) {
// code that relies on the global window object,
// e.g.
myComponent.scrollX = window.scrollX + 100;
}
Methods
scrollPosition()
Returns an object with properties x
and y
reflecting the current scroll position if applicaple, null
otherwise.
Example
import { platform } from '@haensl/services';
if (platform.hasWindow) {
window.addEventListener('scroll', () => {
console.log(platform.scrollPosition());
// will print objects like
// { x: 0, y: 10 }
});
} else if (!platform.hasDocument) {
console.log(platform.scrollPosition());
// will print null since there is neither document nor window!
}
throttle service
The throttle service wraps functionality used to throttle function execution, e.g. debounce
.
Methods
Methods
debounce(fn, debounceMs)
Returns a new function that debounces fn
by debounceMs
milliseconds. Debouncing means fn
is only executed if there are no calls for debounceMs
milliseconds.
Example
import { throttle, platform } from '@haensl/services';
if (platform.hasWindow) {
// only logs when there are no calls
// for 50 milliseconds
const onScroll = throttle.debounce(() => {
console.log(platform.scrollPosition());
}, 50);
window.addEventListener('scroll', onScroll);
}