@straylightagency/utils 1.0.9 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. package/package.json +1 -1
  2. package/src/array/initial.js +1 -1
  3. package/src/array/last.js +3 -1
  4. package/src/array/remove.js +4 -2
  5. package/src/date/clone.js +9 -0
  6. package/src/date/getWeekNumber.js +6 -1
  7. package/src/date/index.js +3 -1
  8. package/src/date/reviver.js +11 -0
  9. package/src/dom/addEventListeners.js +11 -2
  10. package/src/dom/closestElement.js +4 -2
  11. package/src/dom/delegate.js +6 -3
  12. package/src/dom/getElementSizing.js +3 -1
  13. package/src/dom/getFieldsValues.js +3 -1
  14. package/src/dom/onEachElements.js +17 -3
  15. package/src/dom/unlessElementExists.js +20 -10
  16. package/src/dom/whenReady.js +3 -1
  17. package/src/dom/whenResize.js +4 -2
  18. package/src/index.js +18 -2
  19. package/src/misc/attempt.js +20 -0
  20. package/src/misc/base64.js +48 -0
  21. package/src/misc/clipboard.js +7 -5
  22. package/src/misc/debounce.js +4 -4
  23. package/src/misc/index.js +7 -0
  24. package/src/misc/is.js +16 -10
  25. package/src/misc/nextTick.js +4 -3
  26. package/src/misc/retry.js +42 -0
  27. package/src/misc/reviver.js +11 -0
  28. package/src/misc/throttle.js +3 -3
  29. package/src/misc/wait.js +9 -3
  30. package/src/number/format.js +10 -0
  31. package/src/number/index.js +2 -0
  32. package/src/number/random.js +8 -0
  33. package/src/object/filter.js +5 -3
  34. package/src/object/get.js +13 -0
  35. package/src/object/has.js +12 -0
  36. package/src/object/index.js +6 -1
  37. package/src/object/map.js +5 -3
  38. package/src/object/only.js +4 -2
  39. package/src/object/serialize.js +12 -0
  40. package/src/object/set.js +29 -0
  41. package/src/object/unserialize.js +30 -0
  42. package/src/string/capitalFirst.js +14 -0
  43. package/src/string/capitalWords.js +20 -0
  44. package/src/string/index.js +4 -2
  45. package/src/string/interpolate.js +15 -0
  46. package/src/string/slugify.js +28 -0
  47. package/src/string/capitalize.js +0 -7
  48. package/src/string/serialize.js +0 -7
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@straylightagency/utils",
3
- "version": "1.0.9",
3
+ "version": "1.1.0",
4
4
  "description": "Some JavaScript utilities functions",
5
5
  "type": "module",
6
6
  "main": "src/index.js",
@@ -1,5 +1,5 @@
1
1
  /**
2
- * Return the array without the last element
2
+ * Return the array without the last element.
3
3
  *
4
4
  * @param array {[]}
5
5
  * @returns {array}
package/src/array/last.js CHANGED
@@ -1,5 +1,7 @@
1
1
  /**
2
- * @param array {[]}
2
+ * Return the last element of an array.
3
+ *
4
+ * @param {[]} array
3
5
  * @returns {*|undefined}
4
6
  */
5
7
  export default function last(array) {
@@ -1,6 +1,8 @@
1
1
  /**
2
- * @param array {[]}
3
- * @param value {*}
2
+ * Remove a value from the given array, returning a copy.
3
+ *
4
+ * @param {[]} array
5
+ * @param {*} value
4
6
  * @returns {*}
5
7
  */
6
8
  export default function remove(array, value) {
@@ -0,0 +1,9 @@
1
+ /**
2
+ * Clone a Date object.
3
+ *
4
+ * @param {Date} date
5
+ * @returns {Date}
6
+ */
7
+ export default function clone(date) {
8
+ return new Date( date.getTime() );
9
+ }
@@ -1,5 +1,10 @@
1
1
  /**
2
- * @param date {Date}
2
+ * Get the week number of a Date object from the start of the year.
3
+ *
4
+ * @example getWeekNumber( new Date('Mon Mar 16 2026') )
5
+ * => 12
6
+ *
7
+ * @param {Date} date
3
8
  * @returns {number}
4
9
  */
5
10
  export default function getWeekNumber(date) {
package/src/date/index.js CHANGED
@@ -1 +1,3 @@
1
- export { default as getWeekNumber } from "./getWeekNumber.js";
1
+ export { default as getWeekNumber } from "./getWeekNumber.js";
2
+ export { default as clone } from "./clone.js";
3
+ export { default as reviver } from "./reviver.js";
@@ -0,0 +1,11 @@
1
+ /**
2
+ * Function that can be used with JSON.parse to revive Date objects.
3
+ *
4
+ * @param {*} value
5
+ * @returns {Date|undefined}
6
+ */
7
+ export default function reviver(value) {
8
+ if ( typeof value === 'string' && /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}.\d{3}Z$/.test( value ) ) {
9
+ return new Date( value );
10
+ }
11
+ }
@@ -1,6 +1,15 @@
1
1
  /**
2
- * @param element {HTMLElement}
3
- * @param listeners {{}}
2
+ * Define event listeners on an element and returns an object with a callback for removing these listeners on each event.
3
+ *
4
+ * @example const removeListeners = addEventListeners(button, {
5
+ * click: (event) => {...},
6
+ * mouseover: (event) => {...},
7
+ * } );
8
+ * removeListeners.click();
9
+ * => click event has been removed from the button
10
+ *
11
+ * @param {HTMLElement} element
12
+ * @param {{}} listeners
4
13
  */
5
14
  export default function addEventListeners(element, listeners) {
6
15
  Object.fromEntries(
@@ -1,6 +1,8 @@
1
1
  /**
2
- * @param element {HTMLElement}
3
- * @param selector {String}
2
+ * Select the closest element from another.
3
+ *
4
+ * @param {HTMLElement} element
5
+ * @param {string} selector
4
6
  * @returns {HTMLAnchorElement|HTMLElement|HTMLAreaElement|HTMLAudioElement|HTMLBaseElement|HTMLQuoteElement|HTMLBodyElement|HTMLBRElement|HTMLButtonElement|HTMLCanvasElement|HTMLTableCaptionElement|HTMLTableColElement|HTMLDataElement|HTMLDataListElement|HTMLModElement|HTMLDetailsElement|HTMLDialogElement|HTMLDivElement|HTMLDListElement|HTMLEmbedElement|HTMLFieldSetElement|HTMLFormElement|HTMLHeadingElement|HTMLHeadElement|HTMLHRElement|HTMLHtmlElement|HTMLIFrameElement|HTMLImageElement|HTMLInputElement|HTMLLabelElement|HTMLLegendElement|HTMLLIElement|HTMLLinkElement|HTMLMapElement|HTMLMenuElement|HTMLMetaElement|HTMLMeterElement|HTMLObjectElement|HTMLOListElement|HTMLOptGroupElement|HTMLOptionElement|HTMLOutputElement|HTMLParagraphElement|HTMLPictureElement|HTMLPreElement|HTMLProgressElement|HTMLScriptElement|HTMLSelectElement|HTMLSlotElement|HTMLSourceElement|HTMLSpanElement|HTMLStyleElement|HTMLTableElement|HTMLTableSectionElement|HTMLTableCellElement|HTMLTemplateElement|HTMLTextAreaElement|HTMLTimeElement|HTMLTitleElement|HTMLTableRowElement|HTMLTrackElement|HTMLUListElement|HTMLVideoElement|*}
5
7
  */
6
8
  export default function closestElement(element, selector) {
@@ -1,7 +1,10 @@
1
1
  /**
2
- * @param selector {String}
3
- * @param event {String}
4
- * @param handler {Function}
2
+ * Delegate an event through the Document to a selected element. Useful to define an event on an element which is not already created.
3
+ * Returns a callback function that can be used to remove the event listener from the Document.
4
+ *
5
+ * @param {string} selector
6
+ * @param {string} event
7
+ * @param {Function} handler
5
8
  * @returns {function(): any}
6
9
  */
7
10
  export default function delegate(selector, event, handler) {
@@ -1,5 +1,7 @@
1
1
  /**
2
- * @param element {HTMLElement}
2
+ * Get an object with every sizing values of an HTMLElement. Tricks the browser to get values if the element is hidden.
3
+ *
4
+ * @param {HTMLElement} element
3
5
  * @returns {{width: *, height: *, offsetWidth: *, offsetHeight: *, top: number, left: number, bottom: number, right: number,
4
6
  * x: number, y: number, marginLeft: number, marginTop: number, marginBottom: number, marginRight: number,
5
7
  * paddingLeft: number, paddingTop: number, paddingBottom: number, paddingRight: number}}
@@ -1,5 +1,7 @@
1
1
  /**
2
- * @param form {HTMLFormElement}
2
+ * Get an array of the fields value of an HTMLFormElement.
3
+ *
4
+ * @param {HTMLFormElement} form
3
5
  * @returns {{[p: string]: *}}
4
6
  */
5
7
  export default function (form) {
@@ -1,7 +1,13 @@
1
1
  /**
2
- * @param selectorOrParent {String|HTMLElement}
3
- * @param callbackOrSelector {Function|String}
4
- * @param callbackOrNull {Function|null}
2
+ * Execute a callback on each selected HTMLElements. These elements can be reached through a parent.
3
+ * The function returns a NodeList at the end.
4
+ *
5
+ * @example onEachElements('nav .links', links => {...})
6
+ * @example onEachElements(nav, '.links', links => {...})
7
+ *
8
+ * @param {string|HTMLElement} selectorOrParent
9
+ * @param {Function|string} callbackOrSelector
10
+ * @param {Function|null} callbackOrNull
5
11
  * @returns {*}
6
12
  */
7
13
  export default function onEachElements(selectorOrParent, callbackOrSelector, callbackOrNull = null) {
@@ -13,6 +19,14 @@ export default function onEachElements(selectorOrParent, callbackOrSelector, cal
13
19
  return elements;
14
20
  }
15
21
 
22
+ if ( typeof selectorOrParent === 'string' ) {
23
+ selectorOrParent = document.querySelector( selectorOrParent );
24
+ }
25
+
26
+ if ( ! selectorOrParent ) {
27
+ return;
28
+ }
29
+
16
30
  const elements = selectorOrParent.querySelectorAll( callbackOrSelector );
17
31
 
18
32
  elements.forEach( callbackOrNull );
@@ -1,23 +1,33 @@
1
1
  /**
2
- * @param selectorOrParent {String|HTMLElement}
3
- * @param callbackOrSelector {Function|HTMLElement}
4
- * @param callbackOrNull {Function|undefined}
2
+ * Execute a given callback on a selected HTMLElement. Can be used to select a child element through is parent and execute the callback on it.
3
+ * The function always returns the selected (child) element.
4
+ *
5
+ * @example unlessElementExists('main.a button', button => {...});
6
+ * @example unlessElementExists( mainElement , '.a button', button => {...});
7
+ *
8
+ * @param {String|HTMLElement} selectorOrParent
9
+ * @param {Function|HTMLElement} callbackOrSelector
10
+ * @param {Function|undefined} callbackOrNull
5
11
  * @returns {*}
6
12
  */
7
13
  export default function unlessElementExists(selectorOrParent, callbackOrSelector, callbackOrNull = null) {
8
- if ( typeof selectorOrParent === 'string' && typeof callbackOrSelector === 'function' && typeof callbackOrNull !== 'function' ) {
9
- const element = document.querySelector( selectorOrParent );
14
+ if ( typeof selectorOrParent === 'string' ) {
15
+ selectorOrParent = document.querySelector( selectorOrParent );
16
+ }
17
+
18
+ if ( selectorOrParent && typeof callbackOrSelector === 'function' && typeof callbackOrNull !== 'function' ) {
19
+ callbackOrSelector( selectorOrParent );
10
20
 
11
- if ( element ) {
12
- callbackOrSelector( element );
13
- }
21
+ return selectorOrParent;
22
+ }
14
23
 
15
- return element;
24
+ if ( ! selectorOrParent ) {
25
+ return;
16
26
  }
17
27
 
18
28
  const element = selectorOrParent.querySelector( callbackOrSelector );
19
29
 
20
- if ( element && typeof callbackOrNull === 'function' ) {
30
+ if ( element && typeof callbackOrNull === 'function' ) {
21
31
  callbackOrNull( element );
22
32
  }
23
33
 
@@ -1,5 +1,7 @@
1
1
  /**
2
- * @param callbackFn {Function}
2
+ * Execute the given callback when the DOM is ready.
3
+ *
4
+ * @param {Function} callbackFn
3
5
  * @returns void
4
6
  */
5
7
  export default function whenReady(callbackFn) {
@@ -1,6 +1,8 @@
1
1
  /**
2
- * @param callbackFn {Function}
3
- * @param init
2
+ * Execute the given callback when the window is resized. Second parameter allows to run the callback immediately.
3
+ *
4
+ * @param {Function} callbackFn
5
+ * @param {boolean} init
4
6
  */
5
7
  export default function whenResize(callbackFn, init = true) {
6
8
  let ww = window.innerWidth, wh = window.innerHeight;
package/src/index.js CHANGED
@@ -1,12 +1,22 @@
1
- export { default as capitalize } from "./string/capitalize.js";
2
- export { default as serialize } from "./string/serialize.js";
1
+ export { default as capitalFirst } from "./string/capitalFirst.js";
2
+ export { default as capitalWords } from "./string/capitalWords.js";
3
+ export { default as slugify } from "./string/slugify.js";
4
+ export { default as interpolate } from "./string/interpolate.js";
5
+ export { default as format } from "./number/format.js";
6
+ export { default as random } from "./number/random.js";
3
7
  export { default as filter } from "./object/filter.js";
4
8
  export { default as map } from "./object/map.js";
5
9
  export { default as only } from "./object/only.js";
10
+ export { default as serialize } from "./object/serialize.js";
11
+ export { default as unserialize } from "./object/unserialize.js";
12
+ export { default as get } from "./object/get.js";
13
+ export { default as set } from "./object/set.js";
14
+ export { default as has } from "./object/has.js";
6
15
  export { default as clipboard } from "./misc/clipboard.js";
7
16
  export { default as debounce } from "./misc/debounce.js";
8
17
  export { default as nextTick } from "./misc/nextTick.js";
9
18
  export { default as throttle } from "./misc/throttle.js";
19
+ export { default as functionReviver } from "./misc/reviver.js";
10
20
  export { default as addEventListeners } from "./dom/addEventListeners.js";
11
21
  export { default as closestElement } from "./dom/closestElement.js";
12
22
  export { default as delegate } from "./dom/delegate.js";
@@ -17,12 +27,15 @@ export { default as unlessElementExists } from "./dom/unlessElementExists.js";
17
27
  export { default as whenReady } from "./dom/whenReady.js";
18
28
  export { default as whenResize } from "./dom/whenResize.js";
19
29
  export { default as getWeekNumber } from "./date/getWeekNumber.js";
30
+ export { default as clone } from "./date/clone.js";
31
+ export { default as dateReviver } from "./date/reviver.js";
20
32
  export { default as initial } from "./array/initial.js";
21
33
  export { default as last } from "./array/last.js";
22
34
  export { default as remove } from "./array/remove.js";
23
35
 
24
36
  import {wait, seconds, milliseconds} from "./misc/wait.js";
25
37
  import {isClass, isObject, isPlainObject} from "./misc/is.js";
38
+ import {decodeBase64, encodeBase64, isBase64} from "./misc/base64.js";
26
39
 
27
40
  export {
28
41
  wait,
@@ -31,4 +44,7 @@ export {
31
44
  isClass,
32
45
  isObject,
33
46
  isPlainObject,
47
+ decodeBase64,
48
+ encodeBase64,
49
+ isBase64
34
50
  };
@@ -0,0 +1,20 @@
1
+ /**
2
+ * Attempt a Promise, returns the result or the error.
3
+ *
4
+ * @example const [result, error] = attempt(new Promise(...));
5
+ *
6
+ * @param {Promise} promise
7
+ * @return {[]}
8
+ */
9
+ export default async function attempt(promise) {
10
+ let error = undefined;
11
+ let result = undefined;
12
+
13
+ try {
14
+ result = await promise;
15
+ } catch ( e ) {
16
+ error = e;
17
+ }
18
+
19
+ return [ result, error ];
20
+ };
@@ -0,0 +1,48 @@
1
+ /**
2
+ * Decode a base64 value.
3
+ *
4
+ * @param {*} value
5
+ * @return {string|null}
6
+ */
7
+ export function decodeBase64(value) {
8
+ try {
9
+ value = atob( value );
10
+
11
+ if ( typeof value === 'string' ) {
12
+ value = JSON.parse( value );
13
+ }
14
+
15
+ return value;
16
+ } catch ( e ) { /* shhhhhh... */ }
17
+
18
+ return null;
19
+ }
20
+
21
+ /**
22
+ * Encode a value to base64.
23
+ *
24
+ * @param value
25
+ * @return {string|null}
26
+ */
27
+ export function encodeBase64(value) {
28
+ try {
29
+ return btoa( JSON.stringify( value ) );
30
+ } catch (e) { /* shhhhhh... */ }
31
+
32
+ return null;
33
+ }
34
+
35
+ /**
36
+ * Return true if given value is a base64.
37
+ *
38
+ * @param {*} value
39
+ * @return {boolean}
40
+ */
41
+ export function isBase64(value) {
42
+ try {
43
+ atob( value );
44
+ return true;
45
+ } catch ( e ) { /* shhhhhh... */ }
46
+
47
+ return false;
48
+ }
@@ -1,12 +1,14 @@
1
1
  /**
2
- * @param text {String}
2
+ * Push the given string parameter into the clipboard. Use a polyfill if the new 'navigator.clipboard' is not available.
3
+ *
4
+ * @param {string} string
3
5
  * @returns {Promise<void>}
4
6
  */
5
- export default async function clipboard(text) {
6
- if ( typeof ( navigator.clipboard ) == 'undefined' ) {
7
+ export default async function clipboard(string) {
8
+ if ( typeof navigator.clipboard === 'undefined' ) {
7
9
  await new Promise( () => {
8
10
  const textArea = document.createElement("textarea");
9
- textArea.value = text;
11
+ textArea.value = string;
10
12
  textArea.style.position = "fixed"; //avoid scrolling to bottom
11
13
  document.body.appendChild( textArea );
12
14
  textArea.focus();
@@ -18,6 +20,6 @@ export default async function clipboard(text) {
18
20
  } );
19
21
 
20
22
  } else {
21
- await navigator.clipboard.writeText( text );
23
+ await navigator.clipboard.writeText( string );
22
24
  }
23
25
  }
@@ -1,9 +1,9 @@
1
1
  /**
2
- * Execute callback once if called many times during a defined delay
2
+ * Execute callback once if called many times during a defined delay.
3
3
  *
4
- * @param callbackFn {Function}
5
- * @param delay {Number}
6
- * @param immediate {Boolean}
4
+ * @param {Function} callbackFn
5
+ * @param {number} delay
6
+ * @param {boolean} immediate
7
7
  * @returns {(function(): void)|*}
8
8
  */
9
9
  export default function debounce(callbackFn, delay, immediate = false) {
package/src/misc/index.js CHANGED
@@ -2,9 +2,13 @@ export { default as clipboard } from "./clipboard.js";
2
2
  export { default as debounce } from "./debounce.js";
3
3
  export { default as nextTick } from "./nextTick.js";
4
4
  export { default as throttle } from "./throttle.js";
5
+ export { default as attempt } from "./attempt.js";
6
+ export { default as retry } from "./retry.js";
7
+ export { default as reviver } from "./reviver.js";
5
8
 
6
9
  import {wait, seconds, milliseconds} from "./wait.js";
7
10
  import {isClass, isObject, isPlainObject} from "./is.js";
11
+ import {decodeBase64, encodeBase64, isBase64} from "./base64.js";
8
12
 
9
13
  export {
10
14
  wait,
@@ -13,4 +17,7 @@ export {
13
17
  isClass,
14
18
  isObject,
15
19
  isPlainObject,
20
+ decodeBase64,
21
+ encodeBase64,
22
+ isBase64
16
23
  };
package/src/misc/is.js CHANGED
@@ -1,26 +1,32 @@
1
1
  const toString = Object.prototype.toString;
2
2
 
3
3
  /**
4
- * @param obj
4
+ * Check if parameter is an object.
5
+ *
6
+ * @param {*} object
5
7
  * @returns {boolean}
6
8
  */
7
- export function isObject(obj) {
8
- return obj !== null && typeof obj === 'object'
9
+ export function isObject(object) {
10
+ return object !== null && typeof object === 'object'
9
11
  }
10
12
 
11
13
  /**
12
- * @param obj
13
- * @param className
14
+ * Check if parameter is the given className.
15
+ *
16
+ * @param {*} object
17
+ * @param {string} className
14
18
  * @returns {boolean}
15
19
  */
16
- export function isClass(obj, className) {
17
- return isObject( obj ) && toString.call( obj ) === '[object ' + className + ']';
20
+ export function isClass(object, className) {
21
+ return isObject( object ) && toString.call( object ) === '[object ' + className + ']';
18
22
  }
19
23
 
20
24
  /**
21
- * @param obj
25
+ * Check if parameter is a plain object.
26
+ *
27
+ * @param {*} object
22
28
  * @returns {boolean}
23
29
  */
24
- export function isPlainObject(obj) {
25
- return isClass( obj, 'Object' );
30
+ export function isPlainObject(object) {
31
+ return isClass( object, 'Object' );
26
32
  }
@@ -1,11 +1,12 @@
1
1
  /**
2
- * @param callbackFn {Function}
2
+ * Execute the given callback function during a browser's idle periods. Allow to perform background task on the main thread without impacting latency-critical events.
3
+ *
4
+ * @param {Function} callbackFn
3
5
  * @returns {Promise<unknown>}
4
6
  */
5
7
  export default async function nextTick(callbackFn) {
6
8
  return new Promise(
7
- async resolve => requestIdleCallback( () =>
8
- setTimeout( async () => await resolve( await callbackFn() ), 0 )
9
+ async resolve => requestIdleCallback( () => async () => resolve( await callbackFn() )
9
10
  )
10
11
  );
11
12
  }
@@ -0,0 +1,42 @@
1
+ import random from "../number/random.js";
2
+
3
+ /**
4
+ * Retry a callback until success. Fourth parameter can be used to randomly choose the delay between each try.
5
+ *
6
+ * @example
7
+ * retry( 5, nbr_of_try => {
8
+ * if ( do_something() ) {
9
+ * return "ok";
10
+ * }
11
+ *
12
+ * throw "Failed after 5 tries";
13
+ * }, 5000, 10000 );
14
+ *
15
+ * @param {number} times
16
+ * @param {Function} callbackFn
17
+ * @param {number} sleepMsMin
18
+ * @param {number|null} sleepMsMax
19
+ * @returns {Promise<unknown>}
20
+ */
21
+ export default function (times, callbackFn, sleepMsMin = 100, sleepMsMax = null) {
22
+ return new Promise( ( resolve, reject ) => {
23
+ const fn = () => {
24
+ times--;
25
+
26
+ try {
27
+ resolve( callbackFn( times ) );
28
+ } catch ( e ) {
29
+ if ( times < 1 ) {
30
+ reject( e );
31
+ return;
32
+ }
33
+
34
+ const sleepMs = sleepMsMax !== null ? random( sleepMsMin, sleepMsMax ) : sleepMsMin ;
35
+
36
+ setTimeout( fn, sleepMs );
37
+ }
38
+ };
39
+
40
+ fn();
41
+ } );
42
+ };
@@ -0,0 +1,11 @@
1
+ /**
2
+ * Function that can be used with JSON.parse to revive functions.
3
+ *
4
+ * @param {*} value
5
+ * @returns {*|undefined}
6
+ */
7
+ export default function reviver(value) {
8
+ if ( typeof value === 'string' && value.indexOf('function ') === 0 ) {
9
+ return eval( `(${value})` );
10
+ }
11
+ }
@@ -1,8 +1,8 @@
1
1
  /**
2
- * Limit the number of times a callback gets called in a certain time period
2
+ * Limit the number of times a callback gets called in a certain time period.
3
3
  *
4
- * @param callbackFn {Function}
5
- * @param delay {Number}
4
+ * @param {Function} callbackFn
5
+ * @param {number} delay
6
6
  * @returns {(function(): void)|*}
7
7
  */
8
8
  export default function throttle(callbackFn, delay) {
package/src/misc/wait.js CHANGED
@@ -1,5 +1,7 @@
1
1
  /**
2
- * @param timeMs {Number}
2
+ * Stop the main process for a moment defined in milliseconds.
3
+ *
4
+ * @param {number} timeMs
3
5
  * @returns {Promise<unknown>}
4
6
  */
5
7
  export function wait(timeMs) {
@@ -7,7 +9,9 @@ export function wait(timeMs) {
7
9
  }
8
10
 
9
11
  /**
10
- * @param time {Number}
12
+ * Stop the main process for a moment defined in seconds.
13
+ *
14
+ * @param {number} time
11
15
  * @returns {Promise<*>}
12
16
  */
13
17
  export function seconds(time) {
@@ -15,7 +19,9 @@ export function seconds(time) {
15
19
  }
16
20
 
17
21
  /**
18
- * @param timeMs {Number}
22
+ * Alias to `wait`. Stop the main process for a moment defined in milliseconds.
23
+ *
24
+ * @param {number} timeMs
19
25
  * @returns {Promise<*>}
20
26
  */
21
27
  export function milliseconds(timeMs) {
@@ -0,0 +1,10 @@
1
+ /**
2
+ * @param {number} number
3
+ * @param {string} thousandsSeparator
4
+ * @param {string} decimalSeparator
5
+ * @param {number} decimal
6
+ * @returns {string}
7
+ */
8
+ export default function format(number, thousandsSeparator = ' ', decimalSeparator = ',', decimal = 2) {
9
+ return parseFloat( number.toString() ).toFixed( decimal ).replace( '.', decimalSeparator ).replace(/(\d)(?=(\d{3})+(?!\d))/g, '$1' + thousandsSeparator );
10
+ }
@@ -0,0 +1,2 @@
1
+ export { default as format } from "./format.js";
2
+ export { default as random } from "./random.js";
@@ -0,0 +1,8 @@
1
+ /**
2
+ * @param {number} min
3
+ * @param {number} max
4
+ * @returns {number}
5
+ */
6
+ export default function random(min, max) {
7
+ return Math.floor( Math.random() * ( max - min + 1 ) + min );
8
+ }
@@ -1,9 +1,11 @@
1
1
  /**
2
- * @param object {{}}
3
- * @param callbackFn {Function}
2
+ * Filter attributes of an object using a callback function.
3
+ *
4
+ * @param {{}} object
5
+ * @param {Function} callbackFn
4
6
  * @returns {{[p: string]: unknown}}
5
7
  */
6
8
  export default function filter(object, callbackFn) {
7
9
  return Object.fromEntries( Object.entries( object ).
8
- filter( ( [ key, value ] ) => callbackFn( value ) ) );
10
+ filter( ( [ key, value ] ) => callbackFn( value, key ) ) );
9
11
  }
@@ -0,0 +1,13 @@
1
+ /**
2
+ * Get a value using a dot-notated key string.
3
+ *
4
+ * @example get({foo: {bar: {doe: "Bob"}}}, "foo.bar.doe")
5
+ * => "Bob"
6
+ *
7
+ * @param {{}} object
8
+ * @param {string} keys
9
+ * @returns {*}
10
+ */
11
+ export default function (object, keys) {
12
+ return keys.split('.').reduce( ( acc, prop ) => acc[ prop ], object );
13
+ }
@@ -0,0 +1,12 @@
1
+ import get from "./get";
2
+
3
+ /**
4
+ * Get a value using a dot-notated key string
5
+ *
6
+ * @param {{}} object
7
+ * @param {string} keys
8
+ * @returns {*}
9
+ */
10
+ export default function (object, keys) {
11
+ return get( object, keys ) !== undefined;
12
+ }
@@ -1,3 +1,8 @@
1
1
  export { default as filter } from "./filter.js";
2
2
  export { default as map } from "./map.js";
3
- export { default as only } from "./only.js";
3
+ export { default as serialize } from "./serialize.js";
4
+ export { default as unserialize } from "./unserialize.js";
5
+ export { default as only } from "./only.js";
6
+ export { default as set } from "./set.js";
7
+ export { default as get } from "./get.js";
8
+ export { default as has } from "./has.js";
package/src/object/map.js CHANGED
@@ -1,11 +1,13 @@
1
1
  /**
2
- * @param object {{}}
3
- * @param callbackFn {Function}
2
+ * Apply a map callback function over an object.
3
+ *
4
+ * @param {{}} object
5
+ * @param {Function} callbackFn
4
6
  * @returns {{}}
5
7
  */
6
8
  export default function map(object, callbackFn) {
7
9
  return Object.keys( object ).reduce( ( result, key ) => {
8
- result[ key ] = callbackFn( object [ key ] );
10
+ result[ key ] = callbackFn( object [ key ], key );
9
11
  return result;
10
12
  }, {});
11
13
  }
@@ -1,6 +1,8 @@
1
1
  /**
2
- * @param object {{}}
3
- * @param keys {[]}
2
+ * Return an object with specified keys.
3
+ *
4
+ * @param {{}} object
5
+ * @param {[]} keys
4
6
  * @returns {{}}
5
7
  */
6
8
  export default function only(object, keys) {
@@ -0,0 +1,12 @@
1
+ /**
2
+ * Serialize an object into a string, transforms functions into string.
3
+ *
4
+ * @example serialize({foo: {bar: {doe: "Bob", {smith: "John"}}}})
5
+ * => {"foo":{"bar":{"doe":"Bob","smith":"John"}}}
6
+ *
7
+ * @param {{}} object
8
+ * @returns {String}
9
+ */
10
+ export default function serialize(object) {
11
+ return JSON.stringify( object, (key, value) => typeof value === 'function' ? value.toString : value );
12
+ }
@@ -0,0 +1,29 @@
1
+ /**
2
+ * Set a value using a dot-notated key string.
3
+ *
4
+ * @example set({foo: {bar: {doe: "Bob"}}}, "foo.bar.smith", "John");
5
+ * => {foo: {bar: {doe: "Bob", {smith: "John"}}}}
6
+ *
7
+ * @param {{}} object
8
+ * @param {string} keys
9
+ * @param {*} value
10
+ * @returns {*}
11
+ */
12
+ export default function (object, keys, value) {
13
+ const arrKeys = keys.split('.');
14
+ let source = object;
15
+
16
+ arrKeys.map( ( key, i ) => {
17
+ if ( i === arrKeys.length - 1 ) {
18
+ source[ key ] = value;
19
+ }
20
+
21
+ if ( source[ key ] === undefined ) {
22
+ source[ key ] = {};
23
+ }
24
+
25
+ source = source[ key ];
26
+ } );
27
+
28
+ return object;
29
+ }
@@ -0,0 +1,30 @@
1
+ import {reviver as dateReviver} from '../date/reviver.js'
2
+ import {reviver as functionReviver} from '../misc/reviver.js'
3
+
4
+ /**
5
+ * Serialize an object into a string, handling functions and Date objects.
6
+ *
7
+ * @example serialize("{"foo":{"bar":{"doe":"Bob","smith":"John"}}}")
8
+ * => {"foo":{"bar":{"doe":"Bob","smith":"John"}}}
9
+ *
10
+ * @param {string} object
11
+ * @returns {{}}
12
+ */
13
+ export default function unserialize(object) {
14
+ return JSON.parse( object, (key, value) => {
15
+ const revivers = [
16
+ dateReviver,
17
+ functionReviver
18
+ ];
19
+
20
+ let revivedValue = undefined;
21
+
22
+ for ( const reviver of revivers ) {
23
+ if ( ( revivedValue = reviver( value ) ) !== undefined ) {
24
+ return revivedValue;
25
+ }
26
+ }
27
+
28
+ return value;
29
+ } );
30
+ }
@@ -0,0 +1,14 @@
1
+ /**
2
+ * Capitalize the first letter of a string.
3
+ *
4
+ * @example capitalFirst("lazy dog")
5
+ * => "Lazy dog"
6
+ *
7
+ * @param {string} string
8
+ * @returns {string}
9
+ */
10
+ export default function capitalFirst(string) {
11
+ string = string.toString();
12
+
13
+ return string.charAt( 0 ).toUpperCase() + string.slice( 1 );
14
+ }
@@ -0,0 +1,20 @@
1
+ import capitalFirst from "./capitalFirst.js";
2
+
3
+ /**
4
+ * Capitalize every word of a string.
5
+ *
6
+ * @example capitalWords("The quick brown fox jumps over the lazy dog")
7
+ * => "The Quick Brown Fox Jumps Over The Lazy Dog"
8
+ *
9
+ * @param {string} string
10
+ * @returns {string}
11
+ */
12
+ export default function capitalWords(string) {
13
+ const str_arr = string.split(' ');
14
+
15
+ for( let i = 0; i < str_arr.length; i++ ) {
16
+ str_arr[ i ] = capitalFirst( str_arr[ i ] );
17
+ }
18
+
19
+ return str_arr.join(' ');
20
+ }
@@ -1,2 +1,4 @@
1
- export { default as capitalize } from "./capitalize.js";
2
- export { default as serialize } from "./serialize.js";
1
+ export { default as capitalFirst } from "./capitalFirst.js";
2
+ export { default as capitalWords } from "./capitalWords.js";
3
+ export { default as slugify } from "./slugify.js";
4
+ export { default as interpolate } from "./interpolate.js";
@@ -0,0 +1,15 @@
1
+ /**
2
+ * Interpolate a string with data.
3
+ *
4
+ * @example interpolate("The quick :color fox jumps over :who", {color: "brown", who: "the lazy dog"});
5
+ * => "The quick brown fox jumps over the lazy dog"
6
+ *
7
+ * @param {string} string
8
+ * @param {object} replace
9
+ * @returns {string}
10
+ */
11
+ export default function interpolate(string, replace = {}) {
12
+ return string.replace( /:(\w+)/g, ( match, p1 ) =>
13
+ replace[ p1 ] !== undefined ? replace[ p1 ] : ':' + p1
14
+ );
15
+ }
@@ -0,0 +1,28 @@
1
+ /**
2
+ * Slugify a string. Second parameter allows you to choose the separator.
3
+ *
4
+ * @example slugify("The quick brown fox jumps over the lazy dog")
5
+ * => "the-quick-brown-fox-jumps-over-the-lazy-dog"
6
+ *
7
+ * @param {string} string
8
+ * @param {string} separator
9
+ * @returns {string}
10
+ */
11
+ export default function slugify(string, separator = '-') {
12
+ string = string.trim().toLowerCase();
13
+
14
+ /** replaces specials characters with hyphens */
15
+ const from = "ãàáäâẽèéëêìíïîõòóöôøùúüûñç·/_,:;.";
16
+ const to = "aaaaaeeeeeiiiioooooouuuunc-------";
17
+
18
+ for ( let i = 0, l = from.length; i < l; i++ ) {
19
+ string = string.replace( from.charAt( i ), to.charAt( i ) );
20
+ }
21
+
22
+ string = string.normalize('NFD').replace(/[\u0300-\u036f]/g, '');
23
+
24
+ return string
25
+ .replace(/[^a-z0-9 -]/g, '') /** remove any non-alphanumeric characters */
26
+ .replace(/\s+/g, separator ) /** replace spaces with hyphens */
27
+ .replace(/-+/g, separator ); /** remove consecutive hyphens */
28
+ }
@@ -1,7 +0,0 @@
1
- /**
2
- * @param string {String}
3
- * @returns {String}
4
- */
5
- export default function capitalize(string) {
6
- return string.charAt(0).toUpperCase() + string.slice(1);
7
- }
@@ -1,7 +0,0 @@
1
- /**
2
- * @param object {{}}
3
- * @returns {String}
4
- */
5
- export default function serialize(object) {
6
- return Object.entries( object ).map( ( [ key, value ] ) => encodeURIComponent( key ) + '=' + encodeURIComponent( value ) ).join('&');
7
- }