Skip to content

Instantly share code, notes, and snippets.

@ahafidi
Last active October 16, 2018 08:52
Show Gist options
  • Select an option

  • Save ahafidi/dfe641e726e0989d6696448a046e79ca to your computer and use it in GitHub Desktop.

Select an option

Save ahafidi/dfe641e726e0989d6696448a046e79ca to your computer and use it in GitHub Desktop.
/**
*
* @param {string} text
*
* Return a plain JS object providing the number of occurrences of every word containing at least 3 characters from the text
*/
const wordOccurrences = (text) => { // functional programming version
return text
.split(' ')
.filter((token) => token.length > 2)
.reduce((acc, token) => ({
...acc,
[token]: acc[token] ? acc[token] + 1 : 1
}), {});
};
/*
const wordOccurrences = (text) => { // first version...
const tokens = text.split(' ');
const r = {};
tokens.forEach((token) => {
if (token.length <= 2)
return;
if (r[token] !== undefined)
r[token] += 1;
else
r[token] = 1;
});
return r;
};
*/
module.exports = wordOccurrences;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment