UNPKG

find-subsequent

Version:

This package will take two strings and return the two most common pairs in those 2 strings concatenated.

80 lines (66 loc) 2.19 kB
/*This module will return the most common subsequent letters of two strings longestSubsequent function will take two arguments of any strings, arguments doesn't have to be in a specific order. Examples, longestSubsequent("ABAZDC" , "BACBAD") ----> "ADBA" longestSubsequent("AGGTAB", "GXTXAYB") ----> "ABGT" longestSubsequent("ABBA", "ABCABA") -------> "ABBA" */ longestSubsequence = (s1, s2) => { let startingIndex, endingIndex, firstPair, secondPair, matches; startingIndex = 0; firstPair = []; secondPair = []; matches = {}; storeAllPosibilities = (string, pair) => { endingIndex = 0; while (startingIndex !== string.length - 1) { pair.push([string[startingIndex] + string[endingIndex + 1]]); endingIndex++; if (endingIndex == string.length - 1) { startingIndex++; endingIndex = startingIndex; } } startingIndex = 0; endingIndex = string.length - 1; }; storeAllPosibilities(s1, firstPair); storeAllPosibilities(s2, secondPair); appleLength = (length, found, secondFound) => { length += found.length; length += secondFound.length; matches[found[0][0]] = length; return length; }; for (item of firstPair) { let length = 0; let found = firstPair.filter(i => item[0] == i[0]); let secondFound = secondPair.filter(i => item[0] == i[0]); appleLength(length, found, secondFound); } for (item of secondPair) { let length = 0; let found = secondPair.filter(i => item[0] == i[0]); let secondFound = firstPair.filter(i => item[0] == i[0]); appleLength(length, found, secondFound); } const arrayed = []; for (let item in matches) { arrayed.push([item, matches[item]]); } const sorted = arrayed.sort((a, b) => b[1] - a[1]); let string = ""; if ( !sorted[0][0].includes("undefined") && !sorted[1][0].includes("undefined") ) { string = sorted[0][0] + sorted[1][0]; } else if (!sorted[0][0].includes("undefined")) { string = sorted[0][0]; } else { string = sorted[1][0]; } return string; }; export default longestSubsequence;