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

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read more

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

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up