DEV Community

loading...
Play Button Pause Button

3 SIMPLE TRICKS FOR RECURSION OVER A TREE STRUCTURE in JavaScript / NodeJS

JavaScript Joel
Cofounded Host Collective (DiscountASP.net). Cofounded Player Axis (Social Gaming). Computer Scientist and Technology Evangelist with 20+ years of experience with JavaScript!
・1 min read

There are a few simple tricks I use to help simplify the process of creating a recursive function.

Recursion doesn't have to be difficult. These tricks, not only help you in writing and reasoning about a recursive function, but will also help reduce the complexity of that function.

const rxIsoDate = /\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d:[0-5]\d.\d+([+-][0-2]\d:[0-5]\d|Z)/ const isIsoDate = value => typeof value === 'string' && rxIsoDate.test(value) const raw = { a: 1, date: '2020-07-17T01:32:26.206Z', second: { b: 2, createdAt: '2020-07-17T01:32:26.206Z', third: { c: 3, updatedAt: '2020-07-17T01:32:26.206Z' } } } const toJsDate = obj => { if (isIsoDate(obj)) return new Date(obj) if (typeof obj !== 'object') return obj const nextObj = {} for (const [prop, value] of Object.entries(obj)) { nextObj[prop] = toJsDate(value) } return nextObj } toJsDate(raw)

As a BONUS, check out the Runkit here which also includes an example replacing the for loop with reduce https://runkit.com/joelnet/5f1344792ad936001ad53c94

Be sure to subscribe for more videos like this!

Alt Text

Discussion (2)

Collapse
eync profile image
Sanjiv

Nice tricks!
Btw what is your extension called you are using to show spaces and "tabs spacings"? :D

Collapse
joelnet profile image
JavaScript Joel Author

That's not an extension. It's a feature in vscode. Go into your settings, search for "whitespace" and change "Editor: Render Whitespace" to "all". 👍