DEV Community

Discussion on: JavaScript Challenge

Collapse
 
avalander profile image
Avalander

Of course, we can just implement the same algorithm in Javascript, we just need to implement a group function. In this case, I have implemented it as a reducer function so that I can use it in an array method chain.

const last = arr => arr[arr.length - 1]

const appendToLast = (arr, x) => {
  const lastElement = last(arr)
  lastElement.push(x)
  return arr
}

const group = (prev, x) =>
  prev.length === 0
    ? [[ x ]]
    : last(prev)[0] === x
    ? appendToLast(prev, x)
    : [ ...prev, [ x ]]

// Everything above this line is because Javascript doesn't have group built in.

const length = arr => arr.length

const isAlmostLucky = groupedFreqs =>
  groupedFreqs.length === 2 &&
  groupedFreqs[1].length === 1 &&
  groupedFreqs[1][0] === groupedFreqs[0][0] + 1

const isLucky = str => {
  const groupedFreqs = str.split('')
    .sort()
    .reduce(group, [])
    .map(length)
    .sort()
    .reduce(group, [])
  return groupedFreqs.length === 1 ||
    isAlmostLucky(groupedFreqs)
}