Skip to content

Instantly share code, notes, and snippets.

@JO3-W3B-D3V
Created March 8, 2019 09:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JO3-W3B-D3V/816f7de3a706d9529aa6ae85c307f1c6 to your computer and use it in GitHub Desktop.
Save JO3-W3B-D3V/816f7de3a706d9529aa6ae85c307f1c6 to your computer and use it in GitHub Desktop.
This is a simple script to show how you can implement functional style JavaScript.
// Just a short hand function to assist the push function, it simply
// turns a string into an array, and due to surrogate pairs,
// this solution removes all instances of null, then it sorts the array,
// and finally returns it as a string.
const sort = s => [...s].filter(x => x != null).sort().join('');
// A function that will assist the anagrams function, it will
// essentially state whether or not to push a string onto the
// anagrams array or to push null onto the array, there are times
// where this code needs to push null onto the array. But it's okay,
// thanks to the anagrams function, the array gets stripped of all
// null value(s).
const push = o => w => sort(o) === sort(w) && o != w ? o : null;
// A function that takes one argument, which is some dictionary,
// it then returns a function that takes string, to find the
// anagrams that are within the provided dictionary, it then produces
// an array of anagrams.
const anagrams = d => w => d.map(o => push(o)(w)).filter(s => s != null);
// Define some random dictionary and search that dictionary with some
// random string to get back some anagrams, then print the results. All
// of these values are being stored into some variabels, although this is
// just a demonstration of how it works.
const dictionary = ['sign','sing','gins','snig','ings','sgin','sngi','πŸ˜πŸ™πŸšπŸ›'];
const word = 'gins';
const odd = 'πŸ›πŸšπŸ™πŸ˜';
const results = anagrams(dictionary)(word);
const oddCharResult = anagrams(dictionary)(odd);
console.log(results);
console.log(oddCharResult);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment