As asked
Given a nested JavaScript object of design tokens, write a function that outputs a flat array of CSS custom property declarations. For example, { color: { primary: { base: '#007bff' } } } should produce ['--color-primary-base: #007bff']. Handle arbitrary nesting depth.
Sample answer outline
A recursive function that tracks the current path prefix and recurses on objects, writing a CSS custom property string when it reaches a leaf value. Edge cases include null values, arrays (which should probably be skipped or joined), and numeric values like 0 that are falsy. A clean answer separates the traversal from the string formatting and handles the prefix concatenation with a separator that is consistent (dash-joined).
Reference implementation (typescript)
const tokens = {
color: {
primary: { base: '#007bff', hover: '#0056b3' },
neutral: { 100: '#f5f5f5', 900: '#111111' }
},
spacing: { 1: '4px', 2: '8px' }
};
function flattenTokens(obj, prefix = '-') {
// TODO: return string[]
}
console.log(flattenTokens(tokens));
// Expected output:
// ['--color-primary-base: #007bff', '--color-primary-hover: #0056b3', ...]Expect these follow-ups
- How would you modify this to output Swift constants instead of CSS custom properties?
- How would you handle a token value that is itself an object, like a shadow token with x, y, blur, and color keys?