type Tuple<Entity = number> = [Entity, Entity];
type Circle = number;
type Rectangle = Tuple;
type Triangle = [number, number, number];
type Shape = Circle | Rectangle | Triangle;
type ShapeEntity = {
area: number;
shape: Shape
}
type ShapeManager = { [k: number]: Function };
const SHAPES = [[4.23, 6.43], 1.23, 3.444, [1.342, 3.212]] satisfies Shape[];
const shapeManager = (): ShapeManager => {
const circle = (r: Circle) => (Math.PI * r) ** 2;
const rectangle = ([a, b]: Rectangle) => a * b;
const triangle = ([a, b, c]: Triangle) => {
const s = (a + b + c) / 2; // semiPerimeter
return Math.sqrt(s * (s - a) * (s - b) * (s - c));
};
return {
0: circle,
2: rectangle,
3: triangle,
};
};
const sort = (tuple: Tuple<ShapeEntity>) =>
tuple.sort((a, b) => a.area - b.area).map((i) => i.shape);
const getAreas = (shapes: Shape[]) => {
const manager = shapeManager();
const res = shapes.map((shape: Shape) => {
const lines = typeof shape === 'number' ? 0 : shape?.length;
return manager[lines](shape) ?? null;
});
const tuple = res.map((area: number, index: number): ShapeEntity => ({
area,
shape: shapes[index],
})) as Tuple<ShapeEntity>;
return sort(tuple);
};
const sortedArray = getAreas(SHAPES);
console.log(sortedArray);
console.log(sortedArray !== SHAPES);
Created
May 23, 2023 08:30
-
-
Save TupotaValentyn/a3b4f992cb6b5645279e2917b53c84d7 to your computer and use it in GitHub Desktop.
TS Workshop
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment