Skip to content

Instantly share code, notes, and snippets.

@leonidkuznetsov18
Last active April 28, 2021 14:53
Show Gist options
  • Select an option

  • Save leonidkuznetsov18/3b1f8578186d89b3b150543253dd5a77 to your computer and use it in GitHub Desktop.

Select an option

Save leonidkuznetsov18/3b1f8578186d89b3b150543253dd5a77 to your computer and use it in GitHub Desktop.
Price of simple parts
// Task 3. Price of simple parts
// We are selling computer hardware. We have products assembled from parts.
// For example PC is build from motherboard, cpu, hard drive, etc. Some parts are simple: they have no sub parts like CPU.
// When the part has subparts it is not simple. For example PC body has different subparts like covers, screws, etc.
// Every part has price.
// Task:
// For a given list of parts find total price of the all simple parts.
// Design the data structure and write function returning the price for the given list.
interface Part {
id: number;
name: string;
parentId: number | null;
price: number;
}
const PC_PARTS: Part[] = [
{
id: 1,
name: "CPU",
parentId: null,
price: 100,
},
{
id: 2,
name: "HDD",
parentId: null,
price: 50,
},
{
id: 3,
name: "Optical drive",
parentId: null,
price: 10,
},
{
id: 4,
name: "Motherboard",
parentId: null,
price: 140,
},
{
id: 5,
name: "capacitor",
parentId: 4,
price: 5,
},
{
id: 6,
name: "transistor",
parentId: 4,
price: 6,
},
{
id: 7,
name: "PCB",
parentId: 4,
price: 15,
},
{
id: 8,
name: "Power Supply",
parentId: null,
price: 45,
},
{
id: 9,
name: "Power Body",
parentId: 8,
price: 15,
},
{
id: 10,
name: "Power connector",
parentId: 8,
price: 26,
},
];
const findTotalPriceOfSimpleParts = (data: Part[]) => {
return data.reduce((acc, curr) => {
if (curr.parentId !== null) {
acc += curr.price;
}
return acc;
}, 0);
};
console.log(
"findTotalPriceOfSimpleParts",
findTotalPriceOfSimpleParts(PC_PARTS)
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment