Testing 1-2-3

Lee·2022년 7월 2일
0

Algorithm

목록 보기
35/92
post-thumbnail

❓ Testing 1-2-3

Q. Your team is writing a fancy new text editor and you've been tasked with implementing the line numbering.

Write a function which takes a list of strings and returns each line prepended by the correct number.

The numbering starts at 1. The format is n: string. Notice the colon and space in between.

Examples: (Input --> Output)

[ ] --> [ ]

["a", "b", "c"] --> ["1: a", "2: b", "3: c"]

✔ Solution

//#my solution
var number=function(array){
  //your awesome code here
  const result = [];
  
  for (let i = 0, j = 1; i < array.length; i += 1) {
    if (array.length === 0) {
      return `Empty array should return empty array`;
    } else {
      result.push(`${j}: ${array[i]}`);
      j += 1;
    }
  }
  
  return result;
}

//others
var number = function(array) {
  return array.map(function (line, index) {
    return (index + 1) + ": " + line;
  });
}
profile
Lee

0개의 댓글