Created
May 26, 2022 12:17
-
-
Save Avi-E-Koenig/6ef6acf17ad680d6f3b9e91757389d74 to your computer and use it in GitHub Desktop.
Recursive Bill display
This file contains hidden or 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
const itemFactory = () => { | |
return { | |
name: makeid(), | |
price: getRandomInt(1, 100), | |
items: Math.random() < 0.5 ? Array.from({ length: getRandomInt(1, 4) }, itemFactory) : [], | |
} | |
} | |
function getRandomInt(min, max) { | |
min = Math.ceil(min); | |
max = Math.floor(max); | |
return Math.floor(Math.random() * (max - min) + min); //The maximum is exclusive and the minimum is inclusive | |
} | |
function makeid() { | |
var length = 5; | |
var result = ''; | |
var characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'; | |
var charactersLength = characters.length; | |
for (var i = 0; i < length; i++) { | |
result += characters.charAt(Math.floor(Math.random() * | |
charactersLength)); | |
} | |
return result; | |
} | |
const order = itemFactory(); | |
console.log("π ~ file: main.js ~ line 27 ~ order", order, Array.from({ length: getRandomInt(1, 4) }, itemFactory)) | |
const getTotal = (root, sum = 0) => { | |
if (!root) return sum; | |
sum += root.price; | |
if (!root.items) return sum; | |
return root.items.reduce((acc, item) => acc += getTotal(item, acc), sum); | |
} | |
console.log("π ~ file: main.js ~ line 40 ~ getTotal ~ getTotal", getTotal(order)) | |
const logItem = (root, indent = 0, str = '') => { | |
if (!root?.name || !root.price) return; | |
indent += 1; | |
str += Array.from({ length: indent }).join('\t') + `${root.name}:${root.price}\n`; | |
if (!root.items) return str; | |
root.items.forEach(item => str += logItem(item, indent, str)); | |
return str; | |
} | |
console.log("π ~ file: main.js ~ line 44 ~ logItem ~ logItem", logItem(order)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment