I wanted to practice functional programming (fp) without using any library but using vanilla JS only. So I took a problem from Advent of Code (the 1st part of Day 4):
A new system policy has been put in place that requires all accounts to use a passphrase instead of simply a password. A passphrase consists of a series of words (lowercase letters) separated by spaces.
To ensure security, a valid passphrase must contain no duplicate words.
For example:
aa bb cc dd ee
is valid.
aa bb cc dd aa
is not valid - the wordaa
appears more than once.
aa bb cc dd aaa
is valid -aa
andaaa
count as different words.The system's full passphrase list is available as your puzzle input. How many passphrases are valid?
My solution in FP:
const INPUT = `pphsv ojtou brvhsj cer ntfhlra udeh ccgtyzc zoyzmh jum lugbnk vxjnf fzqitnj uyfck blnl impo kxoow nngd worcm bdesehw ... caibh nfuk kfnu llfdbz uxjty yxjut jcea`; const get = input => input.split('\n'); const countDuplicate = words => words.reduce((acc, word) => { return Object.assign(acc, {[word]: (acc[word] || 0) + 1}); }, {}); const onlyUniqueWords = phrases => { const words = phrases.split(' '); const duplicateWords = countDuplicate(words); return !Object.values(duplicateWords).some(w => w > 1); }; const phrasesWithUniqueWords = get(INPUT).filter(onlyUniqueWords); console.log("solution ", phrasesWithUniqueWords.length);
Is there a better way to write it in FP with pure JavaScript, i.e. no additional FP library? Any other improvement suggestions are welcomed.
isValidPassphrase
function. Do you need to count the duplicates? If not, you can probably simplify this.\$\endgroup\$