DEV Community

JP Antunes
JP Antunes

Posted on • Updated on

JS warmup exercises... one-liner edition

There was a post I saw recently that promised a few minutes worth of entertainment... solving 30 javascript interview warmup exercises!

The thing is, after hundreds of lines of code the author only managed to get through the first 10 exercises. As someone who interviews devs and reviews other people's code on a regular basis, it triggered me to solve the exercises but using only one-liners... what can I say, I believe coding exercises should be fun!

//1. write a function that reverses a string
const strReverser = str => [...str].reverse().join('');

//2. Write a function that filters out numbers from a list
const filterNums = arr => arr.map(Number).filter(e => !isNaN(e));

//3. Write a function that finds an element inside an unsorted list
const findElement = (arr, x) => arr.indexOf(x);

//4. Write a function that showcases the usage of closures
const closureMultiplier = a => b => a * b;

//5. What is a Promise? Write a function that returns a Promise
const promiser = f => new Promise(function(resolve, reject) { resolve(f); });

//6. Write a function that flattens a list of items
const flattener = arr => arr.flat(Infinity);

//7. Write a function that finds an element inside a sorted list
//same as 3

//8. Write a function that accepts two numbers a and b and returns both the division of a and b and their modulo of a and b
const divMod = (a, b) => [a / b, a % b];

//9. Write a function that computes the fibonacci number of N
const fibonacci = n => n <= 2 ? n : fibonacci(n-1) + fibonacci(n-2);

//10. Write a function that accepts a string and returns a map with the strings character frequency
const freqMap = arr => arr.reduce( (acc, val) => { acc.set(val, acc.get(val)+1||1); return acc }, new Map());

Top comments (4)

Collapse
 
easrng profile image
easrng

Also, const promiser = f => Promise.resolve(f); or const promiser = async f => f are shorter.

Collapse
 
jpantunes profile image
JP Antunes

Cool! I also have a couple on Fibonnaci here: dev.to/jpantunes/12-ways-to-fibona... and Caesars chiper here: dev.to/jpantunes/render-to-caesar-... if you want to have a look. Actually i have around 100 of these in a collection if you're up for it :-)

Collapse
 
easrng profile image
easrng • Edited

#1 adds commas, it should be .join("")

Collapse
 
jpantunes profile image
JP Antunes

good catch! fixed