Skip to content

Instantly share code, notes, and snippets.

@joynal
Created December 5, 2021 19:26
Show Gist options
  • Save joynal/cb9b9b6fdd30c1fb6ef805266500f706 to your computer and use it in GitHub Desktop.
Save joynal/cb9b9b6fdd30c1fb6ef805266500f706 to your computer and use it in GitHub Desktop.
Count word solution
const { deepStrictEqual } = require('assert')
const mutableApproach = (line) => {
const words = {};
line.split(' ').forEach((key) => {
if (words[key]) {
words[key] += 1;
return;
}
words[key] = 1;
});
return words;
};
const functionalApproach = (line) =>
line.split(' ').reduce((words, key) => {
if (words[key]) {
return { ...words, [key]: words[key] + 1 };
}
return { ...words, [key]: 1 };
}, {});
const input = 'This is some random text and some raddom work';
const want = {
This: 1,
is: 1,
some: 2,
random: 1,
text: 1,
and: 1,
raddom: 1,
work: 1
};
deepStrictEqual(mutableApproach(input), want, "mutable approach failed");
deepStrictEqual(functionalApproach(input), want, "functional approach failed");
console.log('both test passed')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment