Skip to content

Instantly share code, notes, and snippets.

@DMGithinji
Last active July 15, 2020 15:40
Show Gist options
  • Select an option

  • Save DMGithinji/e00cc452c4419698c34b338e95a6d0e6 to your computer and use it in GitHub Desktop.

Select an option

Save DMGithinji/e00cc452c4419698c34b338e95a6d0e6 to your computer and use it in GitHub Desktop.
export function Unscrambler(list: string[]) {
// helper functions
const firstChar = (str: string) => str.charAt(0);
const secondChar = (str: string) => str.charAt(1);
const lastChar = (str: string) => str.charAt(str.length - 1);
const secondLastChar = (str: string) => str.charAt(str.length - 2);
const hasFirst = (str: string): boolean => firstChar(str) === '_';
const hasLast = (str: string): boolean => str.slice(-1) === '_';
const hasTo = (str: string): boolean => (str.split('to')).length > 1;
const hasFrom = (str: string): boolean => (str.split('from')).length > 1;
/**
* Returns obj = {
* 'first': 'N',
* 'N': 'A',
* 'A': 'I',
* 'I': 'R',
* 'R': 'O',
* 'O': 'B',
* 'B': 'I',
*/
const makeNameObj = (strList: string[]): any => {
const nameObj: any = {};
strList.forEach((str) => {
if (hasFirst(str)) {
// '_NtoA' OR '_AfromN' => 'first': 'N'
// 'N': 'A',
if (hasTo(str)){
nameObj.first = secondChar(str);
nameObj[nameObj.first] = lastChar(str);
} else {
nameObj.first = str.slice(-1);
nameObj[nameObj.first] = firstChar(str);
}
} else if (hasLast(str)) {
// '_BtoI' OR 'IfromB_' => 'B': 'I'
if (hasTo(str)){
nameObj[firstChar(str)] = secondLastChar(str);
} else {
nameObj[secondLastChar(str)] = firstChar(str);
}
} else {
// 'RtoO' => 'R': 'O'
if (hasTo(str)) {
nameObj[firstChar(str)] = lastChar(str);
}
// 'OfromR' => 'R': 'O'
else if (hasFrom(str)) {
nameObj[lastChar(str)] = firstChar(str);
}
}
});
return nameObj;
};
/**
* Returns sorted name
*/
const nameSorter = (obj: any): string => {
let getKey = 'first';
let name = '';
let count = 0;
while (count < Object.keys(obj).length) {
name += (obj[getKey]);
getKey = obj[getKey];
count++;
}
return name;
};
const nameMaker = (strList: string[]) => {
const obj = makeNameObj(strList);
return nameSorter(obj);
};
return (nameMaker(list));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment