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

JavaScript Joel - Aug 25 '20 - - Dev Community

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

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .