You can create a JavaScript function called evaluate_css that takes an object representing CSS properties and values, and converts it into a string suitable for inline CSS. Here's how you can implement this function:
function evaluate_css(styles) {
// Check if the input is an object
if (typeof styles !== 'object' || styles === null) {
throw new Error('Input must be a non-nested object');
}
// Initialize an array to hold the CSS string parts
const cssArray = [];
// Iterate over the keys in the object
for (const [key, value] of Object.entries(styles)) {
// Convert camelCase keys to kebab-case
const kebabKey = key.replace(/([A-Z])/g, '-$1').toLowerCase();
// Push the formatted key-value pair to the array
cssArray.push(`${kebabKey}: ${value};`);
}
// Join the array into a single string and return it
return cssArray.join(' ');
}
// Example usage:
const styles = {
backgroundColor: 'red',
fontSize: '16px',
marginTop: '10px'
};
const inlineCss = evaluate_css(styles);
console.log(inlineCss); // Output: "background-color: red; font-size: 16px; margin-top: 10px;"
Explanation:
- Input Validation: The function first checks if the input is a non-nested object. If not, it throws an error.
- Key Conversion: It converts camelCase keys (like
backgroundColor) to kebab-case (like background-color) using a regular expression.
- Building the CSS String: It constructs an array of strings in the format
key: value; and then joins them into a single string.
- Return Value: The final string is returned, which can be used as inline CSS.
You can test the function with different objects to see how it converts them into inline CSS strings.