ocx({})
Installation
The ocx function is a utility for combining different types of values into a single object.
This function is very useful for building style configurations or other properties dynamically by simplifying flexible management based on runtime conditions.
It can accept various input types, such as objects, arrays, functions, or primitive values, and returns an object that combines all relevant properties.
Syntax
function ocx<T extends ocxKey>(...obj: ocxObj<T>[]): ocxAcc<T>;
How ocx works
- Check each input from the parameter sequentially.
- If the input is a function, the function is called, and the result is processed recursively.
- If the input is an array, the elements in it are processed recursively.
- If the input is an object, the properties of the object are merged into the final result.
- Output:
- Primitive values such as strings, numbers, and null are ignored.
- The final result is an object with all the properties of the valid input.
- Repeated values on the same key are overwritten by the last input in the list.
Example of Usage
ocx({ a: 1 }, { b: 2 });
// Output: { a: 1, b: 2 }
ocx([{ a: 1 }, { b: 2 }]);
// Output: { a: 1, b: 2 }
ocx(() => ({ a: 1 }));
// Output: { a: 1 }
ocx(
{ a: 1 },
() => ({ b: 2 }),
[{ c: 3 }, { d: 4 }],
"ignored", // String will be ignored
null // Null will be ignored
);
// Output: {"a":1,"b":2,"c":3,"d":4}
ocx<React.CSSProperties>([
{ baz: "hello", size: !false },
() => ({ foo: "world" }),
undefined,
[true && { margin: "10px" }, () => ({ padd: "5px", "--index": 0 })],
false && [{ out: "1px" }, { border: "cya", "--index": 11 }],
null,
[[true && { bar: null, baz: false, qux: "qux!" }]]
]);
// Output: {"baz":false,"size":true,"foo":"world","margin":"10px","padd":"5px","--index":11,"bar":null,"qux":"qux!"} as `React.CSSProperties & Record<string, any>`
Advantages
- This function is useful for managing style properties dynamically, such as when using a frontend framework with object-based style management.
- Manage object-based configuration structures
- Combine multiple values in a controlled and flexible way