DEV Community

0 seconds of 8 minutes, 3 secondsVolume 90%
Press shift question mark to access a list of keyboard shortcuts
00:00
00:00
08:03
 
JavaScript Joel
JavaScript Joel

Posted on

12 1

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

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

Heroku

Build apps, not infrastructure.

Dealing with servers, hardware, and infrastructure can take up your valuable time. Discover the benefits of Heroku, the PaaS of choice for developers since 2007.

Visit Site

Top comments (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

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". 👍

AWS GenAI LIVE image

Real challenges. Real solutions. Real talk.

From technical discussions to philosophical debates, AWS and AWS Partners examine the impact and evolution of gen AI.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay