quick-n-dirty-utils 0.0.12 → 0.0.15

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 (3) hide show
  1. package/README.md +126 -0
  2. package/dist/util.js +136 -3
  3. package/package.json +1 -1
package/README.md CHANGED
@@ -218,6 +218,43 @@ fetch("http://myurl.com", {
218
218
  })
219
219
  ```
220
220
 
221
+
222
+ #### React State Handlers
223
+
224
+ When a React component uses a state variable to store a list of items any create/update/delete operation
225
+ will have to modify that state variable. To help integrate new/updated items or remove items, the
226
+ following 2 functions are available:
227
+
228
+ ```javascript
229
+ import util from "quick-n-dirty-utils"
230
+ import React from "react"
231
+
232
+ class MyComp extends React.Component {
233
+ constructor(props) {
234
+ super(props)
235
+ this.state = { myList: [] }
236
+ }
237
+ saveItem(item) {
238
+ // doesn't matter if add or update
239
+ this.setState(oldState => ({
240
+ ...oldState,
241
+ myList: util.integrateDbItem(oldState.myList, item),
242
+ }))
243
+ }
244
+ deleteItem(itemId) {
245
+ this.setState(oldState => ({
246
+ ...oldState,
247
+ myList: util.removeDbItem(oldState.myList, itemId),
248
+ }))
249
+ }
250
+ }
251
+ ```
252
+
253
+ Both functions will use the MongoDB convention and use the JSON key `_id` to match items. You can
254
+ override that by providing a 3rd parameter: `util.integrateDbItem(oldState.myList, item, "uid")`
255
+ and `util.removeDbItem(oldState.myList, itemId, "uid")` if for example your JSON key holding the
256
+ unique ID is called `uid`.
257
+
221
258
  #### Login
222
259
 
223
260
  The login functions (including `getAuthJsonHeader()` and `getAuthHeader()`) assume that you use the browser's
@@ -355,6 +392,13 @@ The colors are defaulted to blue (1.0) -> white (0.5) -> red (0.0) and are provi
355
392
 
356
393
  Static field providing a `colors` setting for the `getTriColor(..)` function for red -> yellow -> green.
357
394
 
395
+ #### `hexToRgb(hexValue, alpha)`
396
+
397
+ Converts a colour provided as hexadecimal string into an RGB string, like `rgb(255, 255, 255)` that can
398
+ be used in CSS. It allows an optional `alpha` parameter (default `null`), which will create a string
399
+ like `rgba(255, 255, 255, 0.3)` for an `alpha = 0.3`. The `hexValue` can be provided with or without the
400
+ `#` prefix.
401
+
358
402
  ### Sorting
359
403
 
360
404
  This library introduces a way to sort lists. It has capabilties to sort in ascending or descending order
@@ -527,3 +571,85 @@ const MAPPING = {
527
571
 
528
572
  const DEFAULT_VIEW = util.keyLookup(MAPPING, MAPPING.INVOICE) // this will be "INVOICE"
529
573
  ```
574
+
575
+ #### `jsonGet(object, key)`
576
+
577
+ This simple function has the purpose to access nested JSON objects without
578
+ having to manually check for null at each step.
579
+
580
+ Example:
581
+
582
+ ```javascript
583
+ import util from "quick-n-dirty-utils"
584
+
585
+ const myObject = {
586
+ foo: {
587
+ bar: {
588
+ test: 1,
589
+ },
590
+ },
591
+ }
592
+
593
+ util.jsonGet(myObject, "foo") // will return { bar: { test: 1 } }
594
+ util.jsonGet(myObject, "foo.bar.test") // will return 1
595
+ util.jsonGet(myObject, "foo.test.bar") // will return null
596
+ ```
597
+
598
+ #### `mapListToKeyObject(list, keyOrFunction)`
599
+
600
+ This function allows to map a list of uniform items to a flat JSON object,
601
+ where each object will be stored under a key which is determined from the
602
+ object by accessing a string key or executing a function on that item.
603
+
604
+ The result will be a JSON object. Underneath each key, it will store
605
+ either a single item extracted using the key or function passed or a list
606
+ of item, if multiple items map to the same key.
607
+
608
+ Example:
609
+
610
+ ```javascript
611
+ import util from "quick-n-dirty-utils"
612
+
613
+ const myList = [
614
+ { _id: "a", name: "foo", level: 1, order: 1 },
615
+ { _id: "b", name: "bar", level: 2, order: 2 },
616
+ { _id: "c", name: "test", level: 1, order: 3 },
617
+ ]
618
+
619
+ // using a unique key
620
+ const result1 = util.mapListToKeyObject(myList, "_id")
621
+ /*
622
+ * will return:
623
+ * {
624
+ * "a": { _id: "a", name: "foo", level: 1, order: 1 },
625
+ * "b": { _id: "b", name: "bar", level: 2, order: 2 },
626
+ * "c": { _id: "c", name: "test", level: 1, order: 3 },
627
+ * }
628
+ */
629
+
630
+ // using a key that has duplicates
631
+ const result2 = util.mapListToKeyObject(myList, "level")
632
+ /*
633
+ * will return:
634
+ * {
635
+ * 1: [
636
+ * { _id: "a", name: "foo", level: 1, order: 1 },
637
+ * { _id: "c", name: "test", level: 1, order: 3 },
638
+ * ],
639
+ * 2: { _id: "b", name: "bar", level: 2, order: 2 },
640
+ * }
641
+ */
642
+
643
+ // using a lambda
644
+ const result3 = util.mapListToKeyObject(myList, item => item[level] + item[order])
645
+ /*
646
+ * will return:
647
+ * {
648
+ * 2: { _id: "a", name: "foo", level: 1, order: 1 },
649
+ * 4: [
650
+ * { _id: "b", name: "bar", level: 2, order: 2 },
651
+ * { _id: "c", name: "test", level: 1, order: 3 },
652
+ * ],
653
+ * }
654
+ */
655
+ ```
package/dist/util.js CHANGED
@@ -430,9 +430,14 @@ var util = {
430
430
 
431
431
  /**
432
432
  * Sums up all the values in the provided list
433
- * @param {Array} list
433
+ * @param {Array} list - a list of numbers
434
+ * @returns {Number} the sum of all the items in the list or 0 if the list is empty.
434
435
  */
435
436
  sum: function sum(list) {
437
+ if (list.length === 0) {
438
+ return 0;
439
+ }
440
+
436
441
  return list.reduce(function (a, b) {
437
442
  return a + b;
438
443
  }, 0);
@@ -457,9 +462,9 @@ var util = {
457
462
 
458
463
  /**
459
464
  * Returns an inversed JSON object, where every value becomes the key and maps to its original key.
460
- * @param {object} jsonObject - a flat JSON object, with simple keys and simple values (boolean,
465
+ * @param {object} jsonObject - a flat JSON object, with simple keys and simple values (boolean,
461
466
  * string, number are supported)
462
- * @param {boolean} showWarning - optional flag to print out console warnings in case any key/value
467
+ * @param {boolean} showWarning - optional flag to print out console warnings in case any key/value
463
468
  * pair cannot be mapped or if the JSON object contains duplicates - default = true
464
469
  * @returns {object} a JSON object which maps from each value of the input to the key.
465
470
  */
@@ -505,6 +510,134 @@ var util = {
505
510
  var showWarning = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : true;
506
511
  var reverse = this.reverseMapping(jsonMapping, showWarning);
507
512
  return reverse[lookupValue];
513
+ },
514
+
515
+ /**
516
+ * A function to savely access nested JSON keys in objects. This will handle deeper levels and especially
517
+ * if keys higher up in the hierarchy are not set.
518
+ * @param {Object} object - a JSON object
519
+ * @param {key} key - a string that can include dots (.) for nested JSON keys
520
+ * @returns {Object} null if the key does not exist in the object or the resolved value
521
+ */
522
+ jsonGet: function jsonGet(object, key) {
523
+ if (object == null) {
524
+ return null;
525
+ }
526
+
527
+ if (!key.includes(".")) {
528
+ // simply return the value
529
+ return object[key];
530
+ } // split the key and initialise current object
531
+
532
+
533
+ var current = object;
534
+ var keys = key.split("."); // iterate through keys navigating through
535
+
536
+ keys.forEach(function (k) {
537
+ if (current == null) {
538
+ return;
539
+ }
540
+
541
+ current = current[k];
542
+ }); // return the final value after iterating through all keys
543
+
544
+ return current;
545
+ },
546
+
547
+ /**
548
+ * A function that will map a list of items to a JSON object which contains keys extracted from each item
549
+ * and the value is the object from that list with that key. If multiple values map to the same keys an array
550
+ * of objects will be mapped to that key.
551
+ * @param {Array} list - a list of items
552
+ * @param {string|function} keyOrFunction - a string key (can contain . for nested levels) or a lambda that does
553
+ * the extraction for each item.
554
+ * @returns {Object} a json object mapping from key to an item or list of items
555
+ */
556
+ mapListToKeyObject: function mapListToKeyObject(list, keyOrFunction) {
557
+ // check if it's a simple key mapping or lambda
558
+ var lambda = ["number", "string"].includes(_typeof(keyOrFunction)) ? function (obj) {
559
+ return obj[keyOrFunction];
560
+ } : keyOrFunction;
561
+ var result = {};
562
+
563
+ if (list == null || keyOrFunction == null || list.forEach == null) {
564
+ return result;
565
+ }
566
+
567
+ list.forEach(function (item) {
568
+ var key = lambda(item);
569
+
570
+ if (result[key] == null) {
571
+ // first item for this key
572
+ result[key] = item;
573
+ } else {
574
+ // multiple items for the same key (might have to convert to array)
575
+ if (!Array.isArray(result[key])) {
576
+ // not yet an array, convert the old item stored there
577
+ result[key] = [result[key]];
578
+ } // push the new item
579
+
580
+
581
+ result[key].push(item);
582
+ }
583
+ });
584
+ return result;
585
+ },
586
+
587
+ /**
588
+ * Adds or updates an item in a list of items and returns the updated list. This is useful for React state updates.
589
+ * @param {Array} list - a list of items
590
+ * @param {Object} item - a JSON object to be added to the list or updated, if it already exists
591
+ * @param {string} idKey - the JSON key pointing to the element ID of the item and items in the list
592
+ * @returns {Array} the updated array with the provided `item` either added or updated.
593
+ */
594
+ integrateDbItem: function integrateDbItem(list, item) {
595
+ var idKey = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : "_id";
596
+ var index = list.map(function (i) {
597
+ return i[idKey];
598
+ }).indexOf(item[idKey]);
599
+
600
+ if (index === -1) {
601
+ list.push(item);
602
+ } else {
603
+ list[index] = item;
604
+ }
605
+
606
+ return list;
607
+ },
608
+
609
+ /**
610
+ * Removes an item from a list by referring to the unique item id. This is a simple id filter. Useful for React state updates.
611
+ * @param {Array} list - a list of items
612
+ * @param {string} itemId - the id of the item to remove
613
+ * @param {string} idKey - the JSON key pointing to the element ID of the item and items in the list
614
+ * @returns {Array} the provided list minus the element with the id provided.
615
+ */
616
+ removeDbItem: function removeDbItem(list, itemId) {
617
+ var idKey = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : "_id";
618
+ return list.filter(function (item) {
619
+ return item[idKey] !== itemId;
620
+ });
621
+ },
622
+
623
+ /**
624
+ * Translates a hex colour code into an RGB string. If alpha is provided, it will return an RGBA string. The string can be used in CSS styles
625
+ * @param {string} hexValue - the hex value of colour; can be provided with or without the # and as 3 or 6 digit color
626
+ * @param {Number} alpha - optional: if provided an RGBA (transparency) colour will be returned
627
+ * @returns {string} a colour string usable in colour definitions in CSS
628
+ */
629
+ hexToRgb: function hexToRgb(hexValue) {
630
+ var alpha = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;
631
+ var hex = hexValue.replace("#", "");
632
+ var r = parseInt(hex.length === 3 ? hex.slice(0, 1).repeat(2) : hex.slice(0, 2), 16);
633
+ var g = parseInt(hex.length === 3 ? hex.slice(1, 2).repeat(2) : hex.slice(2, 4), 16);
634
+ var b = parseInt(hex.length === 3 ? hex.slice(2, 3).repeat(2) : hex.slice(4, 6), 16);
635
+
636
+ if (alpha != null) {
637
+ return "rgba(".concat(r, ", ").concat(g, ", ").concat(b, ", ").concat(alpha, ")");
638
+ }
639
+
640
+ return "rgb(".concat(r, ", ").concat(g, ", ").concat(b, ")");
508
641
  }
509
642
  };
510
643
  var _default = util;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "quick-n-dirty-utils",
3
- "version": "0.0.12",
3
+ "version": "0.0.15",
4
4
  "description": "Little useful nuggets for accelerated web development",
5
5
  "scripts": {
6
6
  "build": "./node_modules/.bin/babel src --out-dir ./dist",