Javascript Utility Functions
TypeScript utility functions.
countItemsInMultidimensionalObject
A function that recursively counts the number of selected items in a nested data structure. This function is particularly useful when dealing with hierarchical selection states such as those found in tree views, nested checklists, or multi-level category pickers.
✨ Features
- Handles both arrays and deeply nested objects.
- Returns a detailed breakdown of item counts per level.
- Provides a total count of all selected items.
Data Type
type NestedObject = {
[key: string]: Node | string[];
};
Parameeter
data | NestedObject Or string[] | A nested object or array representing selected items. |
📤 Returns
- If the input is a flat array, it returns a number representing the count of items.
- If the input is a nested object, it returns an object of type SelectionCountsResult:
{
total: number;
result: {
[key: string]: number | { ...nested_object }
}
}
Example
const selection = {
fruits: ["apple", "banana"],
vegetables: {
root: ["carrot", "beet"],
leafy: ["spinach"],
},
grains: {
rice: ["basmati"],
wheat: [],
},
};
const result = countItemsInMultidimensionalObject(selection);
console.log(result);
result:
{
total: 6,
result: {
fruits: 2,
vegetables: {
root: 2,
leafy: 1
},
grains: {
rice: 1,
wheat: 0
}
}
}
formatAsKey
A lightweight utility function that transforms a given string into a valid key name or key by normalizing spaces, removing special characters, and converting to lowercase.
✨ Features
- Converts strings into kebab-case.
- Removes special characters.
- Trims unnecessary dashes from the beginning and end.
🏗️ Parameters
query | string | The string to be formatted. |
📤 Returns
string | A kebab-cased, sanitized string suitable for use as a CSS class name or identifier. |
📘 Example
formatAsKey("Primary Button");
formatAsKey("Save&Continue!");
formatAsKey(" Complex--Key!! ");
formatAsKey("Already-formatted_key");
🔧 Use Cases
- Normalizing user input for CSS class names.
- Generating HTML id attributes from arbitrary labels.
- Creating keys from titles or headings in CMS or UI systems.
🛠 Notes
- Consecutive special characters or whitespace are collapsed into a single dash.
- Leading and trailing dashes are removed for cleanliness.