Skip to content

Instantly share code, notes, and snippets.

@Lucifier129
Created August 21, 2020 03:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Lucifier129/55c84444cad2b5fa9d6b913fb594523e to your computer and use it in GitHub Desktop.
Save Lucifier129/55c84444cad2b5fa9d6b913fb594523e to your computer and use it in GitHub Desktop.
type NullElement = null | undefined;
type BasicElement = number | boolean | string;
type ArrayElement = Array<VElement>;
type ObjectElement = {
props: {
children?: ArrayElement;
};
};
type VElement = NullElement | BasicElement | ArrayElement | ObjectElement;
type Children = ArrayElement;
type FlatChildren = Array<BasicElement>;
const isBasicElement = (child: VElement): child is BasicElement => {
return (
typeof child === "string" ||
typeof child === "number" ||
typeof child === "boolean"
);
};
const isArrayElement = (child: VElement): child is ArrayElement => {
return Array.isArray(child);
};
const isObjectElement = (child: VElement): child is ObjectElement => {
return (
typeof child === "object" &&
!isArrayElement(child) &&
Array.isArray(child?.props?.children)
);
};
const isNullElement = (child: VElement): child is NullElement => {
return child == null;
};
const flattenChildren = (children: Children): FlatChildren => {
return children.reduce<FlatChildren>((flatChildren, child) => {
if (isBasicElement(child)) {
return [...flatChildren, child];
}
if (isArrayElement(child)) {
return [...flatChildren, ...flattenChildren(child)];
}
if (isObjectElement(child)) {
return [...flatChildren, ...flattenChildren(child.props.children ?? [])];
}
return flatChildren;
}, []);
};
const children: Children = [
1,
null,
[2, 3],
{
props: {
children: [4, 5],
},
},
];
console.log(flattenChildren(children));
// [1, 2, 3, 4, 5]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment