Given the name of a class (CustomClass6
) and a string that represents an array with ANY format, it should append the name of the class to the array keeping the format.
Example 1:
Given this string:
"""
const arr = [
CustomClass11,
CustomClass22,
CustomClass33,
CustomClass44,
CustomClass55
];
"""
The function should return:
"""
const arr = [
CustomClass11,
CustomClass22,
CustomClass33,
CustomClass44,
CustomClass55,
CustomClass6
];
"""
Example 2:
Given the string:
"""
const arr = [CustomClass1, CustomClass2, CustomClass3];
"""
It should return:
"""
const arr = [CustomClass1, CustomClass2, CustomClass3, CustomClass6];
"""
Example 3:
"""
const arr = [];
"""
It should return:
"""
const arr = [CustomClass6];
"""
These are the functions I have made this far. I have been able to solve the example 1, but as you can see I have hardcoded the separator to be \n
:
function getStringWithElementAppended(
stringWithArray: string,
classToAppend: string
) {
const openingBraketIndex = stringWithArray.indexOf('[');
const closingBracketIndex = getIndexInString(
stringWithArray,
']',
openingBraketIndex
);
const updatedContent = appendElementToArrayInString(
classToAppend,
openingBraketIndex,
closingBracketIndex,
stringWithArray
);
return updatedContent;
}
function getIndexInString(
String: string,
stringToLookFor: string,
startingIndex: number = 0,
limitIndex: number = String.length,
lastIndex = false
) {
const auxString = String.slice(startingIndex, limitIndex);
if (lastIndex) {
return startingIndex + auxString.lastIndexOf(stringToLookFor);
} else {
return startingIndex + auxString.indexOf(stringToLookFor);
}
}
function appendElementToArrayInString(
elementToAppend: string,
arrayBeginingIndex: number,
arrayEndIndex: number,
String: string
) {
const separationBetweenElements = '\n';
const endOfArrayIndex = getIndexInString(
String,
separationBetweenElements,
arrayBeginingIndex,
arrayEndIndex,
true
);
const previousElementEndIndex = getIndexInString(
String,
separationBetweenElements,
arrayBeginingIndex,
endOfArrayIndex,
true
);
const spaceBetweenElements = String.slice(
previousElementEndIndex + 1,
endOfArrayIndex
);
const whitespaceIndex = spaceBetweenElements.lastIndexOf(' ');
const whitespace = spaceBetweenElements.slice(0, whitespaceIndex + 1);
const contentToAdd =
',' +
separationBetweenElements +
whitespace +
elementToAppend +
separationBetweenElements;
const updatedString =
String.slice(0, endOfArrayIndex) + contentToAdd + String.slice(arrayEndIndex);
return updatedString;
}
At the end of the day, the output should respect the formatting of the input. I am using this code in a script that modifies existing files, and we don't want our SCM to detect a lot of formatting changes.