-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathutilities-string.js
62 lines (59 loc) · 2.15 KB
/
utilities-string.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
// --------------------------------------------------------------------------
// -- utilities-string.js
// -- initial author: Renick Bell ([email protected])
// -- initial creation date: Wed Jun 28 10:08:48 AM CST 2023
// -- contributors: Yiler Huang ([email protected]); Steve Wang ([email protected])
// -- license: GPL 3.0
// --------------------------------------------------------------------------
/**
* Count how many of the same letters there are before a new one is found:
* @param {string} string - the string it counts from.
* @example
* console.log(countLetterChanges('kiisijsdvsddddddggggaa')) //[ 1, 2, 1, 1, 1, 1, 1, 1, 1, 6, 4, 2 ]
* console.log(countLetterChanges('aaaaalllllfdh')) //[ 5, 5, 1, 1, 1 ]
*/
function countLetterChanges(string) {
let counts = [];
let stringArray = string.split('')
let currentCount = 1;
stringArray.forEach((x, i) =>{
if (x !== string[i + 1] && string[i + 1] !== undefined) {
counts.push(currentCount);
currentCount = 1;
}
else if (string[i + 1] !== undefined){
currentCount++;
}
})
counts.push(currentCount); // Push the count of the last letter
return counts;
}
/**
* Shuffles a string in a random way
* @param {string} str - The string to be shuffled
* @example
* console.log(shuffleString('abbbsdfhshfsdoih')) //bhfobsfsdbihsdah
* console.log(shuffleString('HiHowAreYou')) //rHYwoeoHiAu
*/
function shuffleString(str) {
let arr = str.split('');
let len = arr.length;
arr.forEach((x, c) =>{
let i = len - 1 - c
let j = Math.floor(Math.random() * (i + 1));
[arr[i], arr[j]] = [arr[j], arr[i]]; // Use array destructuring for swapping
})
return arr.join('');
}
//One of the versions generated by Chatgpt
/**
* Loops a string by a certain amount of times:
* @param {number} times - Number of times the string should be repeated.
* @param {string} string - The string that should be repeated.
* @example
* console.log(repeatString(2, 'Hi how are you')) //'Hi how are youHi how are you'
* console.log(repeatString(3, 'Ha ')) //'Ha Ha Ha '
*/
function repeatString (times, string){
return A.buildArray(times, x => {return string}).join('')
}