Функция String - Заполнение строки - PullRequest
0 голосов
/ 17 октября 2018

Функция leftPad сделает строку определенной длины, добавив ее слева.Как заставить функцию leftPad работать следующим образом?

// If the input is empty, return an empty string
leftPad('') // ''

// When given just a string, it returns that string
leftPad('abc') // 'abc'

// When given a string and a number, it will pad the string with spaces
// until the string length matches that number. Notice that the code
// below does NOT add four spaces -- rather, it pads the string until
// the length is four
leftPad('abc', 4) // ' abc'

// If the padding given is less than the length of the initial string,
// it just returns the string
leftPad('abc', 2) // 'abc'

// If given a third argument that is a single character, it will pad
// the string with that character
leftPad('abc', 6, 'z') // 'zzzabc'

Это текущий код, который у меня есть для первой части проблемы - если ввод пустой, возвращается пустая строка:

function leftPad (string, padding, character) {
    let result = ""
    if (string.length === 0) {
        return result
    }

    if (string){

    }
}

1 Ответ

0 голосов
/ 17 октября 2018

Я не буду отвечать на весь вопрос, так как кажется, что это домашнее задание.Но вы, вероятно, можете использовать встроенную функцию repeat для построения слева paddedString на основе параметра padding.

function leftPad(string, padding, character) {
  let result = "", padCharacter = ' ';
  if (string.length === 0) {
    return result;
  }
  
  let paddedString = padCharacter.repeat(padding);
  console.log('Left padding will be "' + paddedString + '"');
  // return something
}

leftPad('hello', 5);
leftPad('world', 10);
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...