DEV Community

Cover image for The fastest way to find closing brackets
Eckehard
Eckehard

Posted on

5 1

The fastest way to find closing brackets

Recently I stumbled across the problem to find pairs of brackets in a string. A simple solution could be:

   let s = "the quick { brown } { fox } jumps"
   let ar = s.split("}").map((t,i,ar) => (i<ar.length-1) ? t+"}" : t )

   console.log(ar)
Enter fullscreen mode Exit fullscreen mode

This gives us a nice result, which was ok in my case:

0: 'the quick { brown }'
1: ' { fox }'
2: ' jumps'

This works, but fails for nested brackets. So, how can we deal with paired brackets? If we are evaluating strings on a character basis, we can implement some kind of fancy recursion, but this tends to be slow.

Here is my solution:

let s, tmp, part = '', ar = []
    s = "the quick { brown  { fox }} jumps"

    // split and restore brackets, last element has not bracket! 
    tmp = s.split("}").map((t, i, ar) => (i < ar.length - 1) ? t + '}' : t)

    // fill the result array 'ar'
    tmp.forEach((t) => {
      // set or extend part
      part = (part === '') ? t : part + t
      // find pairs
      if (part.split('{').length === part.split('}').length) { // equal number of brackets?
        ar.push(part.trim()) // => push out
        part = ''
      }
    })

    console.log(ar)
Enter fullscreen mode Exit fullscreen mode

part.split('{').length gives us the number of brackets + 1, so it is easy to compare the number of opening and closing brackets. This gives us the desired result

0: 'the quick { brown { fox }}'
1: 'jumps'

If you have any better way to evaluate pairing brackets, please let me know!

Hint: Solutions based on regEx are usually much slower on JS!

Speedy emails, satisfied customers

Postmark Image

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

Sign up

Top comments (0)

SurveyJS custom survey software

JavaScript Form Builder UI Component

Generate dynamic JSON-driven forms directly in your JavaScript app (Angular, React, Vue.js, jQuery) with a fully customizable drag-and-drop form builder. Easily integrate with any backend system and retain full ownership over your data, with no user or form submission limits.

Learn more

👋 Kindness is contagious

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

Okay