code.ashish.me

Atom feed

Recently added: 02 Count Of Subset Sum, 416 Partition Equal Subset Sum, 01 Subset Sum, 518 Coin Change 2, 983 Minimum Cost For Tickets

058 Length Of Last Word

/**
 * 
 * Ashish Patel
 * e: ashishsushilPatel@gmail.com
 * w: https://ashish.me
 *
 */

/* 
 * Given a string s consists of upper/lower-case alphabets and empty space characters
 * ' ', return the length of last word (last word means the last appearing word if
 * we loop from left to right) in the string.
 * 
 * If the last word does not exist, return 0.
 * 
 * Note: A word is defined as a maximal substring consisting of non-space characters 
 * only.
 * 
 * Example:
 * 
 * Input: "Hello World"
 * Output: 5 
*/

function lengthOfLastWord(value) {
  if(!value) return 0;
  return value.trim().split(' ').pop().length
}

test('length Of Last Word', () => {
  expect(lengthOfLastWord('Hello World')).toEqual(5)
  expect(lengthOfLastWord('a ')).toEqual(1)
  expect(lengthOfLastWord('')).toEqual(0)
  expect(lengthOfLastWord(' ')).toEqual(0)
});

Created 2020-04-09T20:42:31+00:00 · Edit