TL;DR I did a challenge for an anagram creator, I broke down some of the processes. Here is where you can find it in GitHub https://github.com/JacobMGEvans/test-field
Why make one?
I saw someone working on Anagram tester/generator on Twitter, so I decided... I am at the airport for several hours, then a plane ride and need something to do.
The first thing I tried to do was randomly change the index of the elements maybe using .sort()
with a Math.random()
somehow in the mix. I got something that was sorta (bum dum tss) doing what I was hoping for.
Changing the approach, there are usually many different ways to do something.
- The first step for this for me was to still create a pseudo-random number that I could use later. I had an idea that it would take in some input that is different to increase randomness. I thought about adding Date.now() this function but it seemed like overkill for the purpose.
The next step would be the actual anagram code. I will post the whole thing at the end with Jest tests.
The function with param for an incoming string argument would have an array that would be conditionally .push() or .unshift() too.
const randomIntGenerator = ind => Math.floor(ind * Math.random() * 10);
const convertAnagram = str => { const memory = []; }
Ok, cool start.
- From here I want to make a method inside the
convertAnagram()
that uses therandomIntGenerator()
to start changing the string. It would be a conditional based on the random numbers odd or even value which would if even it would push to the array if odd it would unshift inserts the value in the 0 index of an array the logic looking like:
const anagramify = (ele, ind) => randomIntGenerator(ind) % 2 ? memory.push(ele) : memory.unshift(ele);
- Now if you are like, "wait what, where is the loop...?" well done. That last method is made for tacit-programming (point-free) which I had learned from
on his egghead.io course on functional programming, the next bit of logic utilizes the
Array.from(str)
to create an array to.map()
I am fairly certain you could validly[...str].map()
as well. So what is passed into the.map()
? Well it's the method expression anagramify π€£π€£
Array.from(str).map(anagramify);
- The final step is to return the array joined on empty strings to convert the array back to a string.
return memory.join('');
Here is the whole thing plus some comments I use betterComments extension and JSdocs so they dont look like plain multiline comments:
Top comments (4)
astoundingteam.com/anagram/
Cool.
Mmm... I could add better tests lol π
I have since made some more tests and added a typecheck to the input if your interested check out the GitHub link at the top.