lodash#mapValues JavaScript Examples

The following examples show how to use lodash#mapValues. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: hash-utils.js    From ThreatMapper with Apache License 2.0 7 votes vote down vote up
export function hashDifferenceDeep(A, B) {
  // If the elements have exactly the same content, the difference is an empty object.
  // This could fail if the objects are both hashes with different permutation of keys,
  // but this case we handle below by digging in recursively.
  if (stableStringify(A) === stableStringify(B)) return {};

  // Otherwise, if either element is not a hash, always return the first element
  // unchanged as this function only takes difference of hash objects.
  if (!isPlainObject(A) || !isPlainObject(B)) return A;

  // If both elements are hashes, recursively take the difference by all keys
  const rawDiff = mapValues(A, (value, key) => hashDifferenceDeep(value, B[key]));

  // ... and filter out all the empty values.
  return omitBy(rawDiff, value => isEmpty(value));
}
Example #2
Source File: index.js    From datapass with GNU Affero General Public License v3.0 6 votes vote down vote up
getStateFromUrlParams = (defaultState = {}) => {
  const urlParams = new URLSearchParams(window.location.search);

  return mapValues(defaultState, (value, key) => {
    if (!urlParams.has(key)) {
      return value;
    }

    const param = urlParams.getAll(key);

    if (isObject(value)) {
      return JSON.parse(param[0]);
    }

    if (isInteger(value)) {
      return parseInt(param[0]) || value;
    }

    if (isBoolean(value)) {
      return param[0] === 'true';
    }

    return param[0];
  });
}
Example #3
Source File: index.js    From datapass with GNU Affero General Public License v3.0 6 votes vote down vote up
dataProviderParametersToContactInfo = (parameters) =>
  chain(parameters)
    .map(({ label, ...rest }) =>
      label.endsWith(' (Bac à sable)')
        ? { label: label.replace(' (Bac à sable)', ''), ...rest }
        : { label, ...rest }
    )
    .reject(({ email }) => !email)
    .reject(({ label }) => label.endsWith(' (Production)'))
    .reject(({ label }) => label.endsWith(' (FC)'))
    .groupBy(({ email }) => email)
    .mapValues((params) => {
      let labels = params.map(({ label }) => label);
      if (labels.length > 4) {
        labels = labels.slice(0, 4);
        labels.push('etc.');
      }

      return labels.join(', ');
    })
    .toPairs()
    .map(([email, label]) => ({ email, label }))
    .value()
Example #4
Source File: favorites.js    From climatescape.org with MIT License 6 votes vote down vote up
// Accepts raw data from the GetFavorites query and returns an object indexed
// by record_id that has both count and the user's favorite ID
function indexFavoritesData(data) {
  if (!data) return {}

  const counts = keyBy(data.favoritesCount, "recordId")
  const favorites = keyBy(data.favorites, "recordId")

  return mapValues(counts, ({ recordId, count }) => ({
    count, // The total count of favorites
    id: favorites[recordId]?.id, // The user's favorite
  }))
}
Example #5
Source File: node-details-table-row.js    From ThreatMapper with Apache License 2.0 6 votes vote down vote up
function getValuesForNode(node) {
  let values = {};
  ['metrics', 'metadata'].forEach((collection) => {
    if (node[collection]) {
      node[collection].forEach((field) => {
        const result = Object.assign({}, field);
        result.valueType = collection;
        values[field.id] = result;
      });
    }
  });

  if (node.parents) {
    const byTopologyId = groupBy(node.parents, parent => parent.topologyId);
    const relativesByTopologyId = mapValues(byTopologyId, (relatives, topologyId) => ({
      id: topologyId,
      label: topologyId,
      relatives,
      value: relatives.map(relative => relative.label).join(', '),
      valueType: 'relatives',
    }));

    values = {
      ...values,
      ...relativesByTopologyId,
    };
  }

  return values;
}
Example #6
Source File: favorites.js    From goodhere with MIT License 6 votes vote down vote up
// Accepts raw data from the GetFavorites query and returns an object indexed
// by record_id that has both count and the user's favorite ID
function indexFavoritesData(data) {
  if (!data) return {}

  const counts = keyBy(data.favoritesCount, "recordId")
  const favorites = keyBy(data.favorites, "recordId")

  return mapValues(counts, ({ recordId, count }) => ({
    count, // The total count of favorites
    id: favorites[recordId]?.id, // The user's favorite
  }))
}
Example #7
Source File: dragAndDrop.js    From OctoFarm with GNU Affero General Public License v3.0 5 votes vote down vote up
export function dragAndDropGroupEnable(printers) {
  const groupedPrinters = mapValues(groupBy(printers, "group"));
  for (const key in groupedPrinters) {
    if (groupedPrinters.hasOwnProperty(key)) {
      if (key !== "") {
        const currentGroupEncoded = encodeURIComponent(key);
        const dropArea = document.getElementById(
          `dropPanel-${currentGroupEncoded}`
        );

        // Prevent default drag behaviors
        ["dragenter", "dragover", "dragleave", "drop"].forEach((eventName) => {
          dropArea.addEventListener(eventName, preventDefaults, false);
          document.body.addEventListener(eventName, preventDefaults, false);
        });

        // Highlight drop area when item is dragged over it
        ["dragenter", "dragover"].forEach((eventName) => {
          dropArea.addEventListener(
            eventName,
            (event) => {
              activeFile = true;
              highlight(event, dropArea);
            },
            false
          );
        });
        ["dragleave", "drop"].forEach((eventName) => {
          dropArea.addEventListener(
            eventName,
            (event) => {
              activeFile = false;
              unhighlight(event, dropArea);
            },
            false
          );
        });
        dropArea.addEventListener(
          "drop",
          (event) => {
            handleMassDrop(event, groupedPrinters[key]);
          },
          false
        );
      }
    }
  }
}
Example #8
Source File: node-details-table-row.js    From ThreatMapper with Apache License 2.0 5 votes vote down vote up
function getValuesForNode(node) {
  let values = {};
  ['metrics', 'metadata'].forEach(collection => {
    if (node[collection]) {
      node[collection].forEach(field => {
        const result = { ...field };
        result.valueType = collection;
        if (field.id === 'captureStatus') {
          const interfaceList =
            node[collection].filter(row => row.id === 'interfaceNames') || [];
          const { value = '' } = result;
          const match = value.match(/--input-raw ([^\s]+)/gm);
          let interfaceName = '';
          if (match && match.length >= 1) {
            const tempInterfaceName = match[0].split(' ')[1];
            const interfaceListArr = interfaceList[0].value || '';
            if (
              tempInterfaceName.trim().toLowerCase() === 'any' ||
              interfaceListArr.split(';').includes(tempInterfaceName)
            ) {
              interfaceName = tempInterfaceName;
            }
          }

          let captureStatusValue = 'Inactive';
          if (interfaceName) {
            captureStatusValue =
              interfaceName.trim().toLowerCase() !== 'any'
                ? `Active on ${interfaceName} interface`
                : 'Active on all interfaces';
          }
          values[field.id] = { ...result, value: captureStatusValue };
        } else if (field.id === 'user_defined_tags') {
          values[field.id] = {
            ...result,
            value: <TagModalTrigger value={result.value} node={node} />,
          };
        } else if (field.id === 'cloud_provider') {
          values[field.id] = {
            ...result,
            value: result.value || 'Private/On Prem',
          };
        } else {
          values[field.id] = result;
        }
      });
    }
  });

  if (node.parents) {
    const byTopologyId = groupBy(node.parents, parent => parent.topologyId);
    const relativesByTopologyId = mapValues(
      byTopologyId,
      (relatives, topologyId) => ({
        id: topologyId,
        label: topologyId,
        value: relatives.map(relative => relative.label).join(', '),
        valueType: 'relatives',
        relatives,
      })
    );

    values = {
      ...values,
      ...relativesByTopologyId,
    };
  }

  return values;
}
Example #9
Source File: monitoring.updater.js    From OctoFarm with GNU Affero General Public License v3.0 4 votes vote down vote up
function addGroupListeners(printers) {
  const groupedPrinters = mapValues(groupBy(printers, "group"));
  for (const key in groupedPrinters) {
    if (groupedPrinters.hasOwnProperty(key)) {
      const currentGroupEncoded = encodeURIComponent(key);
      //Play button listeners
      let playBtn = document.getElementById("play-" + currentGroupEncoded);
      if (playBtn) {
        playBtn.addEventListener("click", async (e) => {
          e.target.disabled = true;
          for (const printer of groupedPrinters[key]) {
            const opts = {
              command: "start",
            };
            const print = returnPrinterInfo(printer._id);
            const { status } = await OctoPrintClient.jobAction(print, opts, e);
            printActionStatusResponse(status, "print");
          }
        });
      }
      let cancelBtn = document.getElementById("cancel-" + currentGroupEncoded);
      if (cancelBtn) {
        cancelBtn.addEventListener("click", (e) => {
          bootbox.confirm({
            message: "Are you sure you want to cancel the ongoing prints?",
            buttons: {
              cancel: {
                label: "<i class=\"fa fa-times\"></i> Cancel",
              },
              confirm: {
                label: "<i class=\"fa fa-check\"></i> Confirm",
              },
            },
            async callback(result) {
              if (result) {
                e.target.disabled = true;
                for (const printer of groupedPrinters[key]) {
                  const print = returnPrinterInfo(printer._id);
                  const opts = {
                    command: "cancel",
                  };
                  const { status } = await OctoPrintClient.jobAction(
                    print,
                    opts,
                    e
                  );
                  printActionStatusResponse(status, "cancel");
                }
              }
            },
          });
        });
      }
      let restartBtn = document.getElementById(
        "restart-" + currentGroupEncoded
      );
      if (restartBtn) {
        restartBtn.addEventListener("click", async (e) => {
          e.target.disabled = true;
          for (const printer of groupedPrinters[key]) {
            const opts = {
              command: "restart",
            };
            const print = returnPrinterInfo(printer._id);
            const { status } = await OctoPrintClient.jobAction(print, opts, e);
            printActionStatusResponse(status, "restart");
          }
        });
      }
      let pauseBtn = document.getElementById("pause-" + currentGroupEncoded);
      if (pauseBtn) {
        pauseBtn.addEventListener("click", async (e) => {
          e.target.disabled = true;
          for (const printer of groupedPrinters[key]) {
            const opts = {
              command: "pause",
              action: "pause",
            };
            const print = returnPrinterInfo(printer._id);
            const { status } = await OctoPrintClient.jobAction(print, opts, e);
            printActionStatusResponse(status, "pause");
          }
        });
      }
      let resumeBtn = document.getElementById("resume-" + currentGroupEncoded);
      if (resumeBtn) {
        resumeBtn.addEventListener("click", async (e) => {
          e.target.disabled = true;
          for (const printer of groupedPrinters[key]) {
            const opts = {
              command: "pause",
              action: "resume",
            };
            const print = returnPrinterInfo(printer._id);
            const { status } = await OctoPrintClient.jobAction(print, opts, e);
            printActionStatusResponse(status, "resume");
          }
        });
      }
      let filesBtn = document.getElementById(
        "unifiedFiles-" + currentGroupEncoded
      );
      if (filesBtn) {
        filesBtn.addEventListener("click", async () => {
          const idList = [];
          for (const printer of groupedPrinters[key]) {
            idList.push(printer._id);
          }
          const fileList = await OctoFarmClient.get(
            "printers/listUnifiedFiles/" + JSON.stringify(idList)
          );
          drawGroupFiles(fileList);
        });
      }
    }
  }

  return "done";
}
Example #10
Source File: monitoring.updater.js    From OctoFarm with GNU Affero General Public License v3.0 4 votes vote down vote up
async function updateGroupState(printers, clientSettings, view) {
  const uniqueGroupList = [
    ...new Set(printers.map((printer) => printer.group)),
  ];
  uniqueGroupList.forEach((group) => {
    const cleanGroup = encodeURIComponent(group);
    const filteredGroupPrinterList = printers.filter((printer) => {
      if (encodeURIComponent(printer.group) === cleanGroup){
        return printer;
      }
    });
    checkGroupQuickConnectState(filteredGroupPrinterList, cleanGroup);
  })
  printers.forEach((printer, index) => {
    if (printer.group !== "" || !printer.disabled) {
      const elements = grabElements(printer);
      if (!elements?.row) return;
      elements.row.style.order = index;
      if (printer.display) {
        if (elements.row.style.display === "none") {
          switch (view) {
            case "list":
              elements.row.style.display = "table";
              break;
            case "panel":
              elements.row.style.display = "block";
              break;
            case "camera":
              elements.row.style.display = "block";
              break;
            case "group":
              elements.row.style.display = "flex";
              break;
            case "combined":
              elements.row.style.display = "flex";
              break;
          }
        }
      } else {
        if (elements.row.style.display !== "none") {
          elements.row.style.display = "none";
        }
        return;
      }

      let hideOffline = "";
      let hideClosed = "";

      if (!clientSettings?.views?.showDisconnected) {
        hideClosed = "hidden";
      }
      if (!clientSettings?.views?.showOffline) {
        hideOffline = "hidden";
      }

      if (printer.printerState.colour.category === "Active") {
        // Set the state
        if (elements.row.classList.contains(hideClosed)) {
          elements.row.classList.remove(hideClosed);
        }
        if (elements.row.classList.contains(hideOffline)) {
          elements.row.classList.remove(hideOffline);
        }
      } else if (
        printer.printerState.colour.category === "Idle" ||
        printer.printerState.colour.category === "Complete"
      ) {
        if (elements.row.classList.contains(hideClosed)) {
          elements.row.classList.remove(hideClosed);
        }
        if (elements.row.classList.contains(hideOffline)) {
          elements.row.classList.remove(hideOffline);
        }
      } else if (printer.printerState.state === "Disconnected") {
        if (hideClosed !== "") {
          elements.row.classList.add(hideClosed);
        }
      } else if (printer.printerState.colour.category === "Offline") {
        if (hideOffline !== "") {
          elements.row.classList.add(hideOffline);
        }
      }
      UI.doesElementNeedUpdating(
        printer.printerName,
        elements.name,
        "innerHTML"
      );
      UI.doesElementNeedUpdating(
        printer.printerState.state,
        elements.state,
        "innerHTML"
      );
      UI.doesElementNeedUpdating(
        `w-100 badge ${printer.printerState.colour.category}`,
        elements.state,
        "classList"
      );
    }
  });
  const groupedPrinters = mapValues(groupBy(printers, "group"));
  for (const key in groupedPrinters) {
    if (groupedPrinters.hasOwnProperty(key)) {
      if (key !== "") {
        const currentGroupEncoded = encodeURIComponent(key);
        const elements = grabGroupElements(currentGroupEncoded);
        const offlinePrinters = groupedPrinters[key].filter(
          (obj) => obj.printerState.colour.category === "Offline"
        ).length;
        const disconnectedPrinters = groupedPrinters[key].filter(
          (obj) => obj.printerState.state === "Disconnected"
        ).length;
        const idlePrinters = groupedPrinters[key].filter(
          (obj) => obj.printerState.colour.category === "Idle"
        ).length;
        const completePrinters = groupedPrinters[key].filter(
          (obj) => obj.printerState.colour.category === "Complete"
        ).length;
        const activePrinters = groupedPrinters[key].filter(
          (obj) => obj.printerState.colour.category === "Active"
        ).length;
        const pausedPrinters = groupedPrinters[key].filter(
          (obj) => obj.printerState.state === "Paused"
        ).length;
        const pausingPrinters = groupedPrinters[key].filter(
          (obj) =>
            obj.printerState.state === "Pausing" ||
            obj.printerState.state === "Cancelling"
        ).length;
        const filesSelected = groupedPrinters[key].filter(
          (obj) => obj?.currentJob?.fileName !== "No File Selected"
        ).length;

        let combinedProgress = groupedPrinters[key].reduce(function (a, b) {
          return a + b?.["currentJob"]?.["progress"];
        }, 0);

        const actualProgress = combinedProgress / groupedPrinters[key].length;
        UI.doesElementNeedUpdating(
          actualProgress.toFixed(0) + "%",
          elements.progress,
          "innerHTML"
        );
        elements.progress.style.width = actualProgress + "%";

        if (actualProgress < 100) {
          UI.doesElementNeedUpdating(
            "progress-bar progress-bar-striped bg-warning",
            elements.progress,
            "classList"
          );
        } else if (actualProgress === 100) {
          UI.doesElementNeedUpdating(
            "progress-bar progress-bar-striped bg-success",
            elements.progress,
            "classList"
          );
        }

        if (activePrinters === groupedPrinters[key].length) {
          //Set the buttons
          if (elements.start) {
            elements.start.disabled = true;
          }
          if (elements.stop) {
            elements.stop.disabled = false;
          }

          if (pausingPrinters === groupedPrinters[key].length) {
            if (elements.start) {
              elements.start.classList.remove("hidden");
            }
            if (elements.stop) {
              elements.stop.disabled = false;
            }
            if (elements.resume) {
              elements.resume.classList.add("hidden");
            }
            if (elements.pause) {
              elements.pause.disabled = true;
              elements.pause.classList.remove("hidden");
            }
            if (elements.restart) {
              elements.restart.disabled = true;
              elements.restart.classList.add("hidden");
            }
          } else if (pausedPrinters === groupedPrinters[key].length) {
            if (elements.start) {
              elements.start.classList.add("hidden");
            }
            if (elements.resume) {
              elements.resume.disabled = false;
              elements.resume.classList.remove("hidden");
            }
            if (elements.pause) {
              elements.pause.disabled = true;
              elements.pause.classList.add("hidden");
            }
            if (elements.restart) {
              elements.restart.disabled = false;

              elements.restart.classList.remove("hidden");
            }
          } else {
            if (elements.start) {
              elements.start.classList.remove("hidden");
            }

            if (elements.resume) {
              elements.resume.disabled = true;
              elements.resume.classList.add("hidden");
            }
            if (elements.pause) {
              elements.pause.disabled = false;
              elements.pause.classList.remove("hidden");
            }
            if (elements.restart) {
              elements.restart.disabled = true;
              elements.restart.classList.add("hidden");
            }
          }
        } else if (
          idlePrinters === groupedPrinters[key].length ||
          completePrinters === groupedPrinters[key].length
        ) {
          if (filesSelected === groupedPrinters[key].length) {
            if (elements.start) {
              elements.start.disabled = false;
            }
            if (elements.stop) {
              elements.stop.disabled = true;
            }
            if (elements.resume) {
              elements.resume.disabled = true;
            }
            if (elements.pause) {
              elements.pause.disabled = true;
            }
            if (elements.restart) {
              elements.restart.disabled = true;
            }
          } else {
            if (elements.start) {
              elements.start.disabled = true;
            }
            if (elements.stop) {
              elements.stop.disabled = true;
            }
            if (elements.resume) {
              elements.resume.disabled = true;
            }
            if (elements.pause) {
              elements.pause.disabled = true;
            }
            if (elements.restart) {
              elements.restart.disabled = true;
            }
          }
          if (pausedPrinters === groupedPrinters[key].length) {
            if (elements.start) {
              elements.start.classList.add("hidden");
            }
            if (elements.stop) {
              elements.stop.disabled = false;
            }
            if (elements.resume) {
              elements.resume.disabled = false;
              elements.resume.classList.remove("hidden");
            }
            if (elements.pause) {
              elements.pause.disabled = true;
              elements.pause.classList.add("hidden");
            }
            if (elements.restart) {
              elements.restart.disabled = false;
              elements.restart.classList.remove("hidden");
            }
          } else {
            if (elements.start) {
              elements.start.classList.remove("hidden");
            }
            if (elements.resume) {
              elements.resume.disabled = true;
              elements.resume.classList.add("hidden");
            }
            if (elements.pause) {
              elements.pause.disabled = true;
              elements.pause.classList.remove("hidden");
            }
            if (elements.restart) {
              elements.restart.disabled = true;
              elements.restart.classList.add("hidden");
            }
          }
        } else if (disconnectedPrinters === groupedPrinters[key].length) {
          if (elements.start) {
            elements.start.disabled = true;
            elements.start.classList.remove("hidden");
          }
          if (elements.stop) {
            elements.stop.disabled = true;
          }
          if (elements.resume) {
            elements.resume.disabled = true;
            elements.resume.classList.add("hidden");
          }
          if (elements.pause) {
            elements.pause.disabled = true;
            elements.pause.classList.remove("hidden");
          }
          if (elements.restart) {
            elements.restart.disabled = true;
            elements.restart.classList.add("hidden");
          }
        } else if (offlinePrinters === groupedPrinters[key].length) {
          if (elements.start) {
            elements.start.disabled = true;
            elements.start.classList.remove("hidden");
          }
          if (elements.stop) {
            elements.stop.disabled = true;
          }
          if (elements.resume) {
            elements.resume.disabled = true;
            elements.resume.classList.add("hidden");
          }
          if (elements.pause) {
            elements.pause.disabled = true;
            elements.pause.classList.remove("hidden");
          }
          if (elements.restart) {
            elements.restart.disabled = true;
            elements.restart.classList.add("hidden");
          }
        }
      }
    }
  }
}