Reputation: 163
I'm trying to solve a fairly simple kata and find myself stuck to a conditional. I'm trying to return the same integer for a string that has the same letter more than once.
For example, for the string hello
it should return 0.1.2.2.3
.
This is my code so far:
const wordPattern = word => {
word = word.toLowerCase();
let index =[]
for(i=0; i<word.length; i++){
index.includes(i) ? word(i) === index[i] : index.push(i)
}
return index
}
Thanks a lot in advance!
Upvotes: 0
Views: 69
Reputation: 2549
You can look ahead in loop with regular if statement
const wordPattern = word => {
word = word.toLowerCase();
let index =[];
// Because you don't want word letters index,
// you can create separate index
let c = 0;
for(let i=0; i<word.length; i++){
// Add c to index array
index.push(c);
// Increase c index
c++;
// Look ahead and do simple logic
// by decreasing your c index if next
// letter equals current
if(word[i+1] && word[i+1] === word[i]) c--;
}
return index
}
// Test
console.log(wordPattern('Hello').toString());
console.log(wordPattern('Success').toString());
Upvotes: 1
Reputation: 10176
I would use an object, because it provides me the ability to map a key (the letter) to a value (the integer assigned to that letter):
const wordPattern = word => {
word = word.toLowerCase();
const map = {}
const output = []
let counter = 0
for(i=0; i<word.length; i++){
if (!map[word[i]]) {
map[word[i]] = counter
counter++
}
output.push(map[word[i]])
}
return output
}
You could also loop the string using for..of if you are using a modern enough javascript version (es6):
const wordPattern = word => {
word = word.toLowerCase();
const map = {}
const output = []
let counter = 0
for(const l of word) {
if (!map[l]) {
map[l] = counter
counter++
}
output.push(map[l])
}
return output
}
Upvotes: 1