Skip to content

Instantly share code, notes, and snippets.

@unilecs
Last active October 11, 2017 10:55
Show Gist options
  • Save unilecs/bec06747e400e4d26b20fbc3efe7e23d to your computer and use it in GitHub Desktop.
Save unilecs/bec06747e400e4d26b20fbc3efe7e23d to your computer and use it in GitHub Desktop.
Get "degree" of the string
function getDegreeOfString(str, degree) {
let degreeOfStr = "";
const errorMsg = "undefined";
if (degree === 0) return "";
if (degree === 1) return str;
if (degree > 1) {
for (let i = 0; i < (degree - 1); i++) {
degreeOfStr += str;
}
return degreeOfStr;
}
// например, "abcabc", degree = -2
// "abcabc".length = 6 % 2 = 0
// в противном случае, мы не сможем получить корень степени |degree| из str
if (str.length % (degree*(-1))) {
return errorMsg;
}
if (degree < 0) {
const length = str.length / (degree*(-1)); // размер искомой строки
let subStr = str.substring(0, length); // искомая строка
// проверяем заданную строку на вхождение одинаковых значений искомой строки
// str = subStr + subStr + ... + subStr
let index = length;
while (index < str.length) {
let nextSubStr = str.substring(index, index + length);
if (subStr !== nextSubStr) {
return errorMsg;
}
subStr = nextSubStr;
index += length;
}
return subStr;
}
}
console.info(getDegreeOfString("AbcdeAbcdeAbcde", -3)); // Abcde
@mikhail-dvorkin
Copy link

Is is very unnatural to say that k-th root of a string is "power -k". The (~only) natural way would be to call it "power 1/k".

Because in current convention you have s^3 * s^-2 != s, which is very unwanted.

@unilecs
Copy link
Author

unilecs commented Oct 11, 2017

mikhail-dvorkin, actually you're right. Good point.
I changed a comment here a little bit:
"в противном случае, мы не сможем получить корень степени |degree| из str"

Thanks a lot for your feedback.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment