|
| 1 | +const args = process.argv.slice(2); |
| 2 | + |
| 3 | +const test1 = "Codility we test coders"; |
| 4 | + |
| 5 | +if (args.length > 1) { |
| 6 | + args.forEach((arg) => solution(test1, arg)); |
| 7 | +} else { |
| 8 | + solution(test1, Number(args[0])); |
| 9 | +} |
| 10 | + |
| 11 | +function solution(message, K) { |
| 12 | + const curIdx = K - 1; |
| 13 | + if (K >= message.length) { |
| 14 | + result = message; |
| 15 | + } else if (message[curIdx] === " ") { |
| 16 | + result = message.substring(0, curIdx); |
| 17 | + } else if (message[curIdx + 1] === " ") { |
| 18 | + result = message.substring(0, curIdx + 1); |
| 19 | + } else if (message[curIdx - 1] === " ") { |
| 20 | + result = message.substring(0, curIdx - 1); |
| 21 | + } else { |
| 22 | + // berarti ditengah. cari apakah dia punya space awal: |
| 23 | + const prevSpaceIdx = getPrevSpace(message, K - 1); |
| 24 | + if (prevSpaceIdx != -1) { |
| 25 | + console.log("dari sini?"); |
| 26 | + result = message.substring(0, prevSpaceIdx); |
| 27 | + } else { |
| 28 | + result = ""; |
| 29 | + } |
| 30 | + } |
| 31 | + |
| 32 | + console.log("=============== input : ", message, ". limit: ", K); |
| 33 | + console.log("=============== result: ", `"${result}"`); |
| 34 | + |
| 35 | + return result; |
| 36 | +} |
| 37 | + |
| 38 | +function getPrevSpace(message, startIndex) { |
| 39 | + let count = 0; |
| 40 | + for (let i = startIndex; i >= 0; i--) { |
| 41 | + if (i === 0) { |
| 42 | + return -1; |
| 43 | + } |
| 44 | + if (message[i] === " ") { |
| 45 | + return startIndex - count; |
| 46 | + } |
| 47 | + count++; |
| 48 | + } |
| 49 | +} |
0 commit comments