write a js function called evaluate_css that takes in a (non-nested) object of keys and…
- User
write a js function called
evaluate_cssthat takes in a (non-nested) object of keys and values and converts it to an inline css string - Assistant
Here's a JavaScript function that converts a non-nested object of CSS properties into an inline CSS string:
function evaluate_css(styles) { // Check if input is valid if (!styles || typeof styles !== 'object') { return ''; } // Convert object to array of CSS property-value pairs return Object.entries(styles) .map(([key, value]) => { // Convert camelCase to kebab-case const cssProperty = key.replace(/([A-Z])/g, '-$1').toLowerCase(); // Return formatted CSS property-value pair return `${cssProperty}:${value}`; }) .join(';'); } // Example usage: const styleObj1 = { backgroundColor: 'red', fontSize: '16px', marginTop: '10px', border: '1px solid black' }; const styleObj2 = { color: '#333', padding: '5px', fontFamily: 'Arial, sans-serif' }; console.log(evaluate_css(styleObj1)); // Output: "background-color:red;font-size:16px;margin-top:10px;border:1px solid black" console.log(evaluate_css(styleObj2)); // Output: "color:#333;padding:5px;font-family:Arial, sans-serif" console.log(evaluate_css({})); // Output: "" console.log(evaluate_css(null)); // Output: ""This function:
-
Takes a single parameter
styleswhich should be an object containing CSS properties and values -
Includes input validation:
- Returns an empty string if the input is null/undefined
- Returns an empty string if the input is not an object
-
Uses
Object.entries()to convert the object into an array of key-value pairs -
Uses
map()to transform each key-value pair:- Converts camelCase property names to kebab-case (e.g.,
backgroundColortobackground-color) - Formats each pair as a CSS declaration (
property:value)
- Converts camelCase property names to kebab-case (e.g.,
-
Uses
join(';')to combine all declarations into a single string with semicolons as separators
Key features:
- Handles camelCase to kebab-case conversion automatically
- Properly formats the output for use in inline CSS
- Handles empty objects and invalid inputs gracefully
- Works with any valid CSS property-value pairs
You can use this function to generate inline CSS strings that can be applied to HTML elements like this:
const styleObj = { backgroundColor: 'red', fontSize: '16px', marginTop: '10px' }; const cssString = evaluate_css(styleObj); element.setAttribute('style', cssString);Note that this function:
- Assumes all values are valid CSS values (it doesn't do value validation)
- Doesn't handle nested objects (as per the requirement)
- Doesn't add a trailing semicolon (which is valid for inline CSS)
- Preserves the original values exactly as provided (no unit validation or transformation)
-
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.