[04.18.22] Codewars

Simple Pig Latin

Description

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 !

My answer

function pigIt(str){
  let punctuations = /[!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~]/g
  let result = [];
  let array = str.split(' ');
  for (let i = 0; i < array.length; i++) {
    if (!punctuations.test(array[i])) {
      let target = array[i].split('');
      let removed = target.splice(0,1);
      result.push(`${target.join('')}${array[i].charAt(0)}ay`);
    } else {
      result.push(array[i]);
    }
  }
  return result.join(' ');
}

Other solutions

function pigIt(str){
  return str.replace(/(\w)(\w*)(\s|$)/g, "\$2\$1ay\$3")
}
function pigIt(str) {
  return str.replace(/\w+/g, (w) => {
    return w.slice(1) + w[0] + 'ay';
  });
}
function pigIt(str) {
  var arrayWord = str.split(' ');
  return arrayWord.map(function(word) {
    var firstLetter = word.charAt(0);
    return word.slice(1) + firstLetter + 'ay';
  }).join(' ');
}

Wrap up

splice function

The splice() method changes the contents of an array by removing or replacing existing elements and/or adding new elements in place. To access part of an array without modifying it, see slice().

array.splice(start[, deleteCount[, item1[, item2[, ...]]]])

Parameters

start

The index at which to start changing the array.

deleteCount(optional)

An integer indicating the number of elements in the array to remove from start.

item1, item2, ...(optional)

The elements to add to the array, beginning from start.

Return value

An array containing the deleted elements.

Examples

let myFish = ['angel', 'clown', 'mandarin', 'sturgeon']
let removed = myFish.splice(2, 0, 'drum')
// myFish is ["angel", "clown", "drum", "mandarin", "sturgeon"]
let myFish = ['angel', 'clown', 'drum', 'mandarin', 'sturgeon']
let removed = myFish.splice(3, 1)
// myFish is ["angel", "clown", "drum", "sturgeon"]
// removed is ["mandarin"]

slice function

The slice() method returns a shallow copy of a portion of an array into a new array object selected from start to end (end not included) where start and end represent the index of items in that array. The original array will not be modified.

array.slice(start, end)

Parameters

start

Zero-based index at which to start extraction.
A negative index can be used, indicating an offset from the end of the sequence. slice(-2) extracts the last two elements in the sequence.
If start is undefined, slice starts from the index 0.
If start is greater than the index range of the sequence, an empty array is returned.

end(optional)

The index of the first element to exclude from the returned array. slice extracts up to but not including end. For example, slice(1,4) extracts the second element through the fourth element (elements indexed 1, 2, and 3).

Return value

An new array containing the extracted elements.

Examples

const animals = ['ant', 'bison', 'camel', 'duck', 'elephant'];
console.log(animals.slice(2));
// expected output: Array ["camel", "duck", "elephant"]
console.log(animals.slice(2, 4));
// expected output: Array ["camel", "duck"]
console.log(animals.slice(1, 5));
// expected output: Array ["bison", "camel", "duck", "elephant"]
console.log(animals.slice(-2));
// expected output: Array ["duck", "elephant"]
console.log(animals.slice(2, -1));
// expected output: Array ["camel", "duck"]
console.log(animals.slice());
// expected output: Array ["ant", "bison", "camel", "duck", "elephant"]

source: mdn web docs - splice / mdn web docs - slice

Moving Zeros To The End

Description

Write an algorithm that takes an array and moves all of the zeros to the end, preserving the order of the other elements.
moveZeros([false,1,0,1,2,0,1,3,"a"]) // returns[false,1,1,2,1,3,"a",0,0]

My answer

function moveZeros(arr) {
  return arr.filter(a => a !== 0).concat(arr.filter(a => a === 0));
}

Other solutions

var moveZeros = function (arr) {
  return [
    ...(arr.filter(n => n !== 0)),
    ...(arr.filter(n => n === 0))
  ];
}

Remove First and Last Character

Description

It's pretty straightforward. Your goal is to create a function that removes the first and last characters of a string. You're given one parameter, the original string. You don't have to worry with strings with less than two characters.

My answer

function removeChar(str){
  return str.substring(1).slice(0, -1);
};

Other solutions

function removeChar(str) {
  return str.slice(1, -1);
}
function removeChar(str){
 return str.substring(1, str.length-1);
};
function removeChar(str){
  str1 = str.split('');
  str1.shift();
  str1.pop();
  return str1.join('');
};

Wrap up

substring function

The substring() method returns the part of the string between the start and end indexes, or to the end of the string.

array.substring(indexStart, indexEnd)

Parameters

indexStart

The index of the first character to include in the returned substring.

indexEnd(optional)

The index of the first character to exclude from the returned substring.

Return value

A new string containing the specified part of the given string.

Examples

let anyString = 'Mozilla'
// Displays 'M'
console.log(anyString.substring(0, 1))
console.log(anyString.substring(1, 0))
// Displays 'Mozill'
console.log(anyString.substring(0, 6))
// Displays 'lla'
console.log(anyString.substring(4))
console.log(anyString.substring(4, 7))
console.log(anyString.substring(7, 4))
// Displays 'Mozilla'
console.log(anyString.substring(0, 7))
console.log(anyString.substring(0, 10))
// Displays 'illa' the last 4 characters
let anyString = 'Mozilla'
let anyString4 = anyString.substring(anyString.length - 4)
console.log(anyString4)
// Displays 'zilla' the last 5 characters
let anyString = 'Mozilla'
let anyString5 = anyString.substring(anyString.length - 5)
console.log(anyString5)
// Differences between substring() and slice()
let text = 'Mozilla'
console.log(text.substring(5, 2))  // => "zil"
console.log(text.slice(5, 2))      // => ""
// If either or both of the arguments are negative or NaN, the substring() method treats them as if they were 0.
console.log(text.substring(-5, 2))  // => "Mo"
console.log(text.substring(-5, -2)) // => ""

source: mdn web docs

좋은 웹페이지 즐겨찾기