Tuesday, 30 June 2020

The 10-Day JavaScript Challenge

Yay! There's another one started, such fun!

I'll add to this is I go along All done now - such fun.

Day 1

const add = (...a) => a.reduce((t, v) => t + v)

Day 2

const allLongestStrings = a => a.filter(i => i.length === Math.max(...(a.map(a => a.length))))

This is not overly efficient, but it works. Then I got to remembering about default values and altered it to this:

const allLongestStrings = (a, i = Math.max(...(a.map(a => a.length)))) => a.filter(e => e.length === i)

Longer, but we only check for the longest string the once, rather than over each iteration.

Day 3

const allLongestStrings = (a, i = Math.max(...(a.map(a => a.length)))) => a.filter(e => e.length === i)

Day 4

const arrayReplace = (arr, o, n) => arr.map(e => e === o ? n : e)

Day 5

const caseInsensitivePalindrome = (s) => s.toLowerCase().replace(/[\W_]/g, '') === s.toLowerCase().replace(/[\W_]/g, '').split('').reverse().join('')

I like this way because it deals with "A man, a plan, a canal, Panama!". But I really like this one (not mine):

const caseInsensitivePalindrome = s => [...s = s.toLowerCase()].reverse().join`` === s;

Day 6

This was a fun one as we needed to produce three different approaches, here are mine:

const encloseInBrackets = s => `(${s})`
const encloseInBrackets = s => ['(', s, ')'].join('')
const encloseInBrackets = s => ['('].concat(s).concat(')').join('')

This can be improved to this though:

const encloseInBrackets = s => '('.concat(s, ')')
const encloseInBrackets = s => [...s.split('')].map((c, i, a) => i === 0 ? `(${c}` : i === a.length - 1 ? `${c})` : c).join('')

This isn't mine (it's from musa#0677), but I love it:

const encloseInBrackets = s => String.fromCharCode(40, ...s.split('').map((_, i) => s.charCodeAt(i)), 41);

Day 7

const factorialNumber = n => n ? n * factorialNumber(n - 1) : 1

Day 8

const firstDigit = s => s.match(/\d/)[0]

Day 9

const largestNumber = n => ~~[...Array(n)].fill(9).join``

Day 10

A few days late getting this uploaded but I was thinking... This is my attempt but, as was pointed out, it fails when the numbers get too large!

const maxMultiple = (d, b) => ~~(b/d) * d

After my ponder I clocked that this is much better:

const maxMultiple = (d, b) => b - (b % d)

I also played with some other methods:

const maxMultiple = (d, b) => Math.floor(b/d) * d // works
const maxMultiple = (d, b) => ((b/d) >> 0) * d // fails
const maxMultiple = (d, b) => parseInt(b/d, 10) * d // works

Every day really is a school day!

No comments:

Post a Comment