I have a task where I have to iterate thru a string and return a predefined number of chars in a row. So f.i. the string is "Thisisatest" and I have to start on the first position and return two characters. Have to proof them for som uniques (outside that scope) and if not proofed I have to shift the start be one and start on the second position and return two characters. Have to repeat this as long as I found a unique pair of chars or reached the end of the string.
So f.i. first loop: returns Th, then hi, is, si, is, sa, at...
Used this script:
function setInitials(Start,Num,Str){
var initials=""
if(Number(Start) Number(Num)-1 < Str.length){
for (var i = Number(Start); i < Number(Num); i ) {
initials = Str[i];
}
}
return initials
}
where Start ist my Starting point, Num the Number of Chars to return ans Str the string.
But if I try setInitials("2","2","Thisiaatrest") I will get back nothing
CodePudding user response:
after more search I found the problem- the start end endpoint were the same. so the correct working function is:
function setInitials(Start,Num,Str){
var initials=""
var end = Number(Start) Number(Num)-1
if(end-1 < Str.length){
for (var i = Number(Start)-1; i < end; i ) {
initials = Str[i];
}
}
return initials
}
CodePudding user response:
You can check my solution.
function setInitials(start = 0, span = 0, str = '') {
const [obj, tmp] = [{}, []];
let [left, right, count] = [start, start, 0];
while (right < str.length) {
const char = str[right];
if (!obj[char]) {
obj[char] = 1;
count ;
} else {
obj[char] ;
}
tmp.push(char);
while (left < str.length && right - left 1 === span) {
const _char = str[left];
if (count === span) return tmp.join('');
obj[_char] = Math.max(obj[_char] - 1, 0);
if (obj[_char] === 0) count--;
tmp.shift();
left ;
}
right ;
}
return 'Not Found';
}
console.log(setInitials(0, 2, 'Thisisatest'));
console.log(setInitials(2, 2, 'Thisiaatrest'));
console.log(setInitials(0, 3, 'aaaabcaa'));
console.log(setInitials(0, 3, 'aaaaaaaa'));