I’m working on a speech to text module and, often enough, we have the following scenario:
var str1 = "It was great, I finally had some time to"
var str2 = "had some time to relax and catch up on my reading."
I need a function that will go through str1
backwards and detect if it has a duplicated sentence from str2
to combine without repeating it, into a concise final phrase like:
var result = "It was great, I finally had some time to relax and catch up on my reading."
This is my attempt:
function formPhrase(str1, str2) {
const words1 = str1.split(' ');
const words2 = str2.split(' ');
const uniqueWords = [];
for (const word of words1) {
if (!uniqueWords.includes(word)) {
uniqueWords.push(word);
}
}
for (const word of words2) {
if (!uniqueWords.includes(word)) {
uniqueWords.push(word);
}
}
const result = uniqueWords.join(' ');
return result;
}
var str1 = "It was great, I finally had some time to"
var str2 = "had some time to relax and catch up on my reading."
console.log(formPhrase(str1, str2))
It does work for str1
and str2
, but if the concatenated area has words that is also included on other parts of str1
and str2
, it will fail, example: this code transforms this
and transforms this string
.
3
Answers
To achieve this, you can try using the following function:
Find the longest phrase from the beginning of the second sentence that the first sentence ends with. We slice phrases by spaces for speed: