findNeedle.js (8kyu 12)

Codewars 알고리즘 풀이


Description

  • Write a function that takes an array full of junk but containing one ‘needle’.
    • junk로 가득하지만 ‘needle’ 하나를 포함하는 배열이 주어진다.
  • After your function find the needle it should return a message that says: ‘found the needle at position (index)’
    • ‘needle’의 인덱스와 함께 메시지를 반환한다.



Solution 01

function findNeedle(haystack) {
  for (let i = 0; i < haystack.length; i++) {
    if (haystack[i] === 'needle') {
      return 'found the needle at position ' + i;
    }
  }
}

findNeedle([1, 2, 'needle', 4]);  // found the needle at position 2
findNeedle([1, 'a piece of hay', true, 4, 'needle', undefined]);  // found the needle at position 4


Solution 02

function findNeedle(haystack) {
  return 'found the needle at position ' + haystack.indexOf('needle');
}

findNeedle([1, 2, 'needle', 4]);  // found the needle at position 2
findNeedle([1, 'a piece of hay', true, 4, 'needle', undefined]);  // found the needle at position 4


Solution 03

function findNeedle(haystack) {
  return 'found the needle at position ${haystack.indexOf('needle')}';
}

findNeedle([1, 2, 'needle', 4]);  // found the needle at position 2
findNeedle([1, 'a piece of hay', true, 4, 'needle', undefined]);  // found the needle at position 4