5 kyu · algorithms

Simple Pig Latin

Regular ExpressionsAlgorithms

Move the first letter of each word to the end of it, then add "ay" to the end of the word. Leave punctuation marks untouched.

Examples

pigIt('Pig latin is cool'); // igPay atinlay siay oolcay
pigIt('Hello world !');     // elloHay orldway !
pigIt(@"Pig latin is cool"); // => @"igPay atinlay siay oolcay"
pigIt(@"Hello world !");     // => @"elloHay orldway !"
pig_it('Pig latin is cool') # igPay atinlay siay oolcay
pig_it('Hello world !')     # elloHay orldway !
pig_it('Pig latin is cool') # igPay atinlay siay oolcay
pig_it('Hello world !')     # elloHay orldway !
Kata.PigIt("Pig latin is cool"); // igPay atinlay siay oolcay
Kata.PigIt("Hello world !");     // elloHay orldway !
pig_it("Pig latin is cool");   // igPay atinlay siay oolcay
pig_it("Hello world !");       // elloHay orldway
PigLatin.pigIt('Pig latin is cool'); // igPay atinlay siay oolcay
PigLatin.pigIt('Hello world !');     // elloHay orldway !
(piglatin/pig-it "Pig latin is cool") ; "igPay atinlay siay oolcay"
(piglatin/pig-it "Hello world !")     ; "elloHay orldway !"
pigIt('Pig latin is cool'); // igPay atinlay siay oolcay
pigIt('Hello world !');     // elloHay orldway !
      PigIt str = 'Pig latin is cool' => result = 'igPay atinlay siay oolcay'
      PigIt str = 'Hello world !'     => result = 'elloHay orldway !

Solutions

01-solution.jsView on GitHub ↗
function pigIt(str) {
  const words = str.split(" ");
  const res = [];
  for (let i = 0; i < words.length; i++) {
    const word = words[i];
    if (/[.!?\\-]/.test(word)) {
      res.push(word);
    } else {
      const c = word.split("");
      const lc = c.splice(1, c.length);
      const w = [...lc, c[0], "ay"];
      res.push(w.join(""));
    }
  }
  return res.join(" ");
}

function pigIt(str) {
  const words = str.split(" ");
  return words
    .reduce((snc, word) => {
      if (/[.!?\\-]/.test(word)) {
        snc.push(word);
      } else {
        const c = word.split("");
        const lc = c.splice(1, c.length);
        const w = [...lc, c[0], "ay"];
        snc.push(w.join(""));
      }
      return snc;
    }, [])
    .join(" ");
}