Created
August 6, 2021 03:08
-
-
Save carlohcs/eb16e31ffbdf32a9ff45d3081be8c89a to your computer and use it in GitHub Desktop.
Get variables with defined name in JSON file created by style-dictionary
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment