I don't remember where I saw it (maybe one of your other posts) but I recently saw a technique for ensuring uniqueness of array elements - iterate over the elements and just return the equality of the current index to the value returned by calling Array.indexOf(). Using that technique here, Array.every() can be used to ensure each word is unique.
With that technique, there is no need to count the number of occurrences of each word and hence the reduction can be removed. Thus countDuplicate can be eliminated and onlyUniqueWords can be simplified like below:
const onlyUniqueWords = phrases => {
const words = phrases.split(' ');
return words.every((word, index) => words.indexOf(word) === index);
};
Here is a jsPerf comparing this technique with the original. The original appears to be ~83-86% slower.
In the snippet below (and the jsPerf mentioned above), I replaced the 3rd line (i.e. ...) with two lines similar to those in the problem description. The first inserted line has unique words and the second does not.
const INPUT =
`pphsv ojtou brvhsj cer ntfhlra udeh ccgtyzc zoyzmh jum lugbnk
vxjnf fzqitnj uyfck blnl impo kxoow nngd worcm bdesehw
aa bb cc dd
aa bb cc dd ee cc
caibh nfuk kfnu llfdbz uxjty yxjut jcea`;
const get = input => input.split('\n');
const onlyUniqueWords = phrases => {
const words = phrases.split(' ');
return words.every((word, index) => words.indexOf(word) === index);
};
const phrasesWithUniqueWords = get(INPUT).filter(onlyUniqueWords);
console.log("solution ", phrasesWithUniqueWords.length);
P.S. I feel like this technique could very easily apply to your subsequent post for the 2nd part of this..., but perhaps for the sake of varying ideas, I shall refrain from mentioning this in that post...