Search code examples
javascriptarraysstringprototype

How to split a string of sentences in half, into an array of two strings, each with as similar in length as possible?


I have an interesting problem here. I have a couple of Javascript strings like so:

var a = "A few sentences. For tests. The point of these sentences is to be used as examples.";
var b = "A couple more sentences. These ones are shorter.";
var c = "Blah. Foo. Bar. Baz. Test. Test 2. Test C.";
var d = "Test sentence.";

I would like to extend the string prototype to have a method to split each string into an array of two strings, each with as similar a number of characters as mathematically possible, while also maintaining whole sentences.

The results I'd be looking for:

a.halve() // ["A few sentences. For tests.", "The point of these sentences is to be used as examples."]
b.halve() // ["A couple more sentences.", "These ones are shorter."]
c.halve() // ["Blah. Foo. Bar. Baz.", "Test. Test 2. Test C."]
d.halve() // ["Test sentence.", ""]

If I do a.length / 2, I get the ideal target length of the two strings... I'm just having a hard time split'ing and joining them in the right order.


Solution

  • A quick solution :)

    Reflect.set(String.prototype, 'halve', function(){
      let mid = Math.floor(this.length/2)
      let i = mid - 1, j = mid, sep = mid
      while(j<this.length) {
        if(this[i]==='.') { sep = i + 1; break }
        if(this[j]==='.') { sep = j + 1; break }
        i--
        j++
      }
      return [this.slice(0,sep), this.slice(sep)]
    })
    
    var a = "A few sentences. For tests. The point of these sentences is to be used as examples.";
    var b = "A couple more sentences. These ones are shorter.";
    var c = "Blah. Foo. Bar. Baz. Test. Test 2. Test C.";
    var d = "Test sentence.";
    
    console.log(a.halve()) // ["A few sentences. For tests.", "The point of these sentences is to be used as examples."]
    console.log(b.halve()) // ["A couple more sentences.", "These ones are shorter."]
    console.log(c.halve()) // ["Blah. Foo. Bar. Baz.", "Test. Test 2. Test C."]
    console.log(d.halve()) // ["Test sentence.", ""]