Serialise a style object to CSS text
Server renderers, email builders and canvas-to-HTML exporters all need to print a style object as real CSS text. Two decisions define the behaviour: which numbers get px, and which entries are dropped.
Implement styleObjectToCss(style). Walk the object's own keys in insertion order. Skip any entry whose value is null, undefined or the empty string "". Convert each remaining key from camelCase to kebab-case by replacing each uppercase letter with a - and its lowercase form; a key beginning with -- is a custom property and is used exactly as written.
A numeric value has px appended, except for the five unitless properties opacity, zIndex, fontWeight, lineHeight and flexGrow, which are printed as the bare number. This applies to 0 too, so marginTop: 0 prints as margin-top: 0px. Any other value is printed with String(value).
Each declaration is printed as name: value; — one space after the colon and a trailing semicolon, including on the last one — and declarations are joined by a single space. An object with nothing to print returns the empty string "".
What it has to do
- Convert camelCase keys to kebab-case, leaving
--customproperties as written. - Append
pxto numeric values except foropacity,zIndex,fontWeight,lineHeightandflexGrow. - Skip entries whose value is
null,undefinedor"". - Print every declaration as
name: value;and join them with a single space. - Return
""for an empty object.
Your workspace
Ready to check it?
5 tests run against your code, right here in your browser. Sign in to claim the XP when you pass.
AI Crack & Solution Assist
Stuck? Get instant AI hints or break down the optimal solution.
Stuck? The javascript course covers everything this challenge needs.