Created
August 21, 2020 03:31
-
-
Save Lucifier129/55c84444cad2b5fa9d6b913fb594523e to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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