Skip to content

Instantly share code, notes, and snippets.

@carlohcs
Created August 6, 2021 03:08
Show Gist options
  • Select an option

  • Save carlohcs/eb16e31ffbdf32a9ff45d3081be8c89a to your computer and use it in GitHub Desktop.

Select an option

Save carlohcs/eb16e31ffbdf32a9ff45d3081be8c89a to your computer and use it in GitHub Desktop.

Revisions

  1. carlohcs created this gist Aug 6, 2021.
    58 changes: 58 additions & 0 deletions GetVariables.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,58 @@
    import variables from "path/variables.json";

    /**
    * Return variables as "$prefix-color-brand-..."
    *
    * @param {String} name
    * @returns {String}
    */
    function formatVariableName(name) {
    const prefix = "$prefix";
    name = name.replace(/([A-Z])/g, "-$&").toLowerCase();
    name = name.replace(/([0-9]{2})/g, "-$&");

    return `${prefix}${name}`;
    }

    /**
    * Returns an array with variables containing the defined name
    *
    * @param {String} name
    * @returns {Array}
    */
    function GetVariables(name) {
    const finalVariables = [];

    if (!name) {
    throw new Error("Define a name to find.");
    }

    const getItems = (items) => {
    try {
    const keys = Object.keys(items);

    if (keys.length > 0) {
    keys.forEach((key) => {
    if (items[key].name && items[key].name.indexOf(name) > -1) {
    finalVariables.push({
    name: formatVariableName(items[key].name),
    value: items[key].value,
    });

    delete items[key];
    } else {
    if (typeof items[key] === "object") {
    getItems(items[key]);
    }
    }
    });
    }
    } catch (error) {}

    return finalVariables;
    };

    return getItems(variables);
    }

    export default GetVariables;