loading...

Discussion on: Daily Challenge #180 - SMS Shortener

Collapse
avaq profile image
Aldwin Vlasblom

A recursive solution in JavaScript:

const pattern = /\s+(\S)(\S*)$/;
const minify = sms => 
  sms.length <= 160 || sms.match (pattern) === null ? sms :
  minify (sms.replace (pattern, (_, c, w) => c.toUpperCase() + w))

With comments:

// A regular expression that matches any white-space followed by a captured 
// non-white-space character, and any number of non white-space characters
// separately captured, all at the end of the input.
const pattern = /\s+(\S)(\S*)$/;

const minify = sms =>
  // If the input SMS is already short enough, or has no white-space
  // characters, we just return it.
  sms.length <= 160 || sms.match (pattern) === null ? sms :

  // If it does have white-space, we remove the last occurrence and
  // uppercase the captured character. Then we minify the resulting
  // SMS recursively.
  minify (sms.replace (pattern, (_, c, w) => c.toUpperCase() + w))