Prompt:
/*
  You will be given a string of words separated by commas or spaces. Your task is
  to split the string into words and return an array of the words.

  For example:
  wordsString("Hi, my name is John") == ["Hi", "my", "name", "is", "John"]
  wordsString("One, two, three, four, five, six") == ["One", "two", "three", "four", "five", "six"]
  */
const wordsString = (s) => {

const testWordsString = () => {
  console.assert(
    JSON.stringify(wordsString('Hi, my name is John')) ===
    JSON.stringify(['Hi', 'my', 'name', 'is', 'John'])
  )
  console.assert(
    JSON.stringify(wordsString('One, two, three, four, five, six')) ===
    JSON.stringify(['One', 'two', 'three', 'four', 'five', 'six'])
  )
  console.assert(
    JSON.stringify(wordsString('Hi, my name')) ===
    JSON.stringify(['Hi', 'my', 'name'])
  )
  console.assert(
    JSON.stringify(wordsString('One,, two, three, four, five, six,')) ===
    JSON.stringify(['One', 'two', 'three', 'four', 'five', 'six'])
  )
  console.assert(JSON.stringify(wordsString('')) === JSON.stringify([]))
  console.assert(
    JSON.stringify(wordsString('ahmed     , gamal')) ===
    JSON.stringify(['ahmed', 'gamal'])
  )
}

testWordsString()

'Hi, my name is John'
'One, two, three, four, five, six'
'Hi, my name'
'One,, two, three, four, five, six,'
''
'ahmed     , gamal'


Prompt:
/*This function takes two positive numbers x and y and returns the
  biggest even integer number that is in the range [x, y] inclusive. If
  there's no such number, then the function should return -1.

  For example:
  chooseNum(12, 15) = 14
  chooseNum(13, 12) = -1
  */
const chooseNum = (x, y) => {

  for (let i = y; i >= x; i--) {
    if (i % 2 == 0) {return i }
  }
  return -1
}

const testChooseNum = () => {
  console.assert(chooseNum(12, 15) === 14)
  console.assert(chooseNum(13, 12) === -1)
  console.assert(chooseNum(33, 12354) === 12354)
  console.assert(chooseNum(5234, 5233) === -1)
  console.assert(chooseNum(6, 29) === 28)
  console.assert(chooseNum(27, 10) === -1)
  console.assert(chooseNum(7, 7) === -1)
  console.assert(chooseNum(546, 546) === 546)
}

testChooseNum()


Prompt:
/*You are given two positive integers n and m, and your task is to compute the
  average of the integers from n through m (including n and m).
  Round the answer to the nearest integer and convert that to binary.
  If n is greater than m, return -1.
  Example:
  roundedAvg(1, 5) => "0b11"
  roundedAvg(7, 5) => -1
  roundedAvg(10, 20) => "0b1111"
  roundedAvg(20, 33) => "0b11010"
  */
const roundedAvg = (n, m) => {

const testRoundedAvg = () => {
  console.assert(roundedAvg(1, 5) === '0b11')
  console.assert(roundedAvg(7, 13) === '0b1010')
  console.assert(roundedAvg(964, 977) === '0b1111001011')
  console.assert(roundedAvg(996, 997) === '0b1111100101')
  console.assert(roundedAvg(560, 851) === '0b1011000010')
  console.assert(roundedAvg(185, 546) === '0b101101110')
  console.assert(roundedAvg(362, 496) === '0b110101101')
  console.assert(roundedAvg(350, 902) === '0b1001110010')
  console.assert(roundedAvg(197, 233) === '0b11010111')
  console.assert(roundedAvg(7, 5) === -1)
  console.assert(roundedAvg(5, 1) === -1)
  console.assert(roundedAvg(5, 5) === '0b101')
}

testRoundedAvg()


Prompt:
/*Given a list of positive integers x. return a sorted list of all
  elements that hasn't any even digit.

  Note: Returned list should be sorted in increasing order.

  For example:
  >>> uniqueDigits([15, 33, 1422, 1])
  [1, 15, 33]
  >>> uniqueDigits([152, 323, 1422, 10])
  []
  */
const uniqueDigits = (x) => {

  let p = []
  for (let i = 0; i < x.length; i++) {
    let h = x[i]
    let boo = 1
    while (h > 0) {
      let r = h % 10
      if (r % 2 == 0) {
        boo = 0;
        break;
      }
      h = (h - r) / 10
    }
    if (boo) {
      p.push(x[i])
    }
  }
  for (let j = 0; j < p.length; j++) {
    let ind = j
    for (let k = j + 1; k < p.length; k++) {
      if (p[k] < p[ind]) {
        ind = k
      }
    }
    if (ind > j) {
      let tmp = p[j]
      p[j] = p[ind]
      p[ind] = tmp
    }
  }
  return p
}

const testUniqueDigits = () => {
  console.assert(
    JSON.stringify(uniqueDigits([15, 33, 1422, 1])) ===
    JSON.stringify([1, 15, 33])
  )
  console.assert(
    JSON.stringify(uniqueDigits([152, 323, 1422, 10])) === JSON.stringify([])
  )
  console.assert(
    JSON.stringify(uniqueDigits([12345, 2033, 111, 151])) ===
    JSON.stringify([111, 151])
  )
  console.assert(
    JSON.stringify(uniqueDigits([135, 103, 31])) === JSON.stringify([31, 135])
  )
}

testUniqueDigits()


Prompt:
/*
  Given an array of integers, sort the integers that are between 1 and 9 inclusive,
  reverse the resulting array, and then replace each digit by its corresponding name from
  "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine".

  For example:
    arr = [2, 1, 1, 4, 5, 8, 2, 3]
          -> sort arr -> [1, 1, 2, 2, 3, 4, 5, 8]
          -> reverse arr -> [8, 5, 4, 3, 2, 2, 1, 1]
    return ["Eight", "Five", "Four", "Three", "Two", "Two", "One", "One"]

    If the array is empty, return an empty array:
    arr = []
    return []

    If the array has any strange number ignore it:
    arr = [1, -1 , 55]
          -> sort arr -> [-1, 1, 55]
          -> reverse arr -> [55, 1, -1]
    return = ['One']
  */
const byLength = (arr) => {

  p = []
  for (let i = 0; i < arr.length; i++) {
    if (arr[i] > 0 && arr[i] < 10) { p.push(arr[i]) }
  }
  for (let j = 0; j < p.length; j++) {
    let ind = j
    for (let k = j + 1; k < p.length; k++) {
      if (p[k] > p[ind]) {
        ind = k
      }
    }
    if (ind > j) {
      let tmp = p[j]
      p[j] = p[ind]
      p[ind] = tmp
    }
  }
  let l = ['One', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine']
  let t = []
  for (let j = 0; j < p.length; j++) {
    t.push(l[p[j]-1])
  }
  return t
}

const testByLength = () => {
  console.assert(
    JSON.stringify(byLength([2, 1, 1, 4, 5, 8, 2, 3])) ===
    JSON.stringify([
      'Eight',
      'Five',
      'Four',
      'Three',
      'Two',
      'Two',
      'One',
      'One',
    ])
  )
  console.assert(JSON.stringify(byLength([])) === JSON.stringify([]))
  console.assert(
    JSON.stringify(byLength([1, -1, 55])) === JSON.stringify(['One'])
  )
  console.assert(
    JSON.stringify(byLength([1, -1, 3, 2])) ===
    JSON.stringify(['Three', 'Two', 'One'])
  )
  console.assert(
    JSON.stringify(byLength([9, 4, 8])) ===
    JSON.stringify(['Nine', 'Eight', 'Four'])
  )
}

testByLength()


Prompt:
/* Implement the function f that takes n as a parameter,
  and returns a list of size n, such that the value of the element at index i is the factorial of i if i is even
  or the sum of numbers from 1 to i otherwise.
  i starts from 1.
  the factorial of i is the multiplication of the numbers from 1 to i (1 * 2 * ... * i).
  Example:
  f(5) == [1, 2, 6, 24, 15]
  */
const f = (n) => {

  let f = 1
  let p = 0
  let k = []
  for (let i = 1; i <= n; i++) {
    p += i;
    f *= i;
    if (i % 2 == 0) { k.push(f) }
    else { k.push(p) }
  }
  return k
}

const testF = () => {
  console.assert(JSON.stringify(f(5)) === JSON.stringify([1, 2, 6, 24, 15]))
  console.assert(
    JSON.stringify(f(7)) === JSON.stringify([1, 2, 6, 24, 15, 720, 28])
  )
  console.assert(JSON.stringify(f(1)) === JSON.stringify([1]))
  console.assert(JSON.stringify(f(3)) === JSON.stringify([1, 2, 6]))
}

testF()


Prompt:
/*
  Given a positive integer n, return a list that has the number of even and odd
  integer palindromes that fall within the range(1, n), inclusive.

  Example 1:

      Input: 3
      Output: [1, 2]
      Explanation:
      Integer palindrome are 1, 2, 3. one of them is even, and two of them are odd.

  Example 2:

      Input: 12
      Output: [4, 6]
      Explanation:
      Integer palindrome are 1, 2, 3, 4, 5, 6, 7, 8, 9, 11. four of them are even, and 6 of them are odd.

  Note:
      1. 1 <= n <= 10^3
      2. returned list has the number of even and odd integer palindromes respectively.
  */
const evenOddPalindrome = (n) => {

  let e = 0
  let o = 0
  for (let i = 1; i <= n; i++) {
    let k = i.toString()
    let p = 1
    for (let j = 0; j < k.length; j++) {
      if (k[j] != k[k.length - j - 1]) {
        p = 0;
        break;
      }
    }
    if (p == 1) {
      if (k % 2 == 0) { e++ }
      else { o++ }
    }
  }
  return [e, o]
}

const testEvenOddPalindrome = () => {
  console.assert(
    JSON.stringify(evenOddPalindrome(123)) === JSON.stringify([8, 13])
  )
  console.assert(
    JSON.stringify(evenOddPalindrome(12)) === JSON.stringify([4, 6])
  )
  console.assert(
    JSON.stringify(evenOddPalindrome(3)) === JSON.stringify([1, 2])
  )
  console.assert(
    JSON.stringify(evenOddPalindrome(63)) === JSON.stringify([6, 8])
  )
  console.assert(
    JSON.stringify(evenOddPalindrome(25)) === JSON.stringify([5, 6])
  )
  console.assert(
    JSON.stringify(evenOddPalindrome(19)) === JSON.stringify([4, 6])
  )
  console.assert(
    JSON.stringify(evenOddPalindrome(9)) === JSON.stringify([4, 5])
  )
  console.assert(
    JSON.stringify(evenOddPalindrome(1)) === JSON.stringify([0, 1])
  )
}

testEvenOddPalindrome()


Prompt:
/*
  Write a function countNums which takes an array of integers and returns
  the number of elements which has a sum of digits > 0.
  If a number is negative, then its first signed digit will be negative:
  e.g. -123 has signed digits -1, 2, and 3.
  >>> countNums([]) == 0
  >>> countNums([-1, 11, -11]) == 1
  >>> countNums([1, 1, 2]) == 3
  */
const countNums = (arr) => {

  let p = 0
  for (let i = 0; i < arr.length; i++) {
    let h = arr[i]
    if (h > 0) {
      p++;
      continue;
    }
    let k = 0
    h = -h
    while (h >= 10) {
      k += h % 10;
      h = (h - h % 10) / 10;
    }
    k -= h;
    if (k > 0) { p++ }
  }
  return p
}

const testCountNums = () => {
  console.assert(countNums([]) === 0)
  console.assert(countNums([-1, -2, 0]) === 0)
  console.assert(countNums([1, 1, 2, -2, 3, 4, 5]) === 6)
  console.assert(countNums([1, 6, 9, -6, 0, 1, 5]) === 5)
  console.assert(countNums([1, 100, 98, -7, 1, -1]) === 4)
  console.assert(countNums([12, 23, 34, -45, -56, 0]) === 5)
  console.assert(countNums([-0, 1 ** 0]) === 1)
  console.assert(countNums([1]) === 1)
}

testCountNums()


Prompt:
/*We have an array 'arr' of N integers arr[1], arr[2], ..., arr[N].The
  numbers in the array will be randomly ordered. Your task is to determine if
  it is possible to get an array sorted in non-decreasing order by performing
  the following operation on the given array:
      You are allowed to perform right shift operation any number of times.

  One right shift operation means shifting all elements of the array by one
  position in the right direction. The last element of the array will be moved to
  the starting position in the array i.e. 0th index.

  If it is possible to obtain the sorted array by performing the above operation
  then return true else return false.
  If the given array is empty then return true.

  Note: The given list is guaranteed to have unique elements.

  For Example:

  moveOneBall([3, 4, 5, 1, 2])==>true
  Explanation: By performin 2 right shift operations, non-decreasing order can
               be achieved for the given array.
  moveOneBall([3, 5, 4, 1, 2])==>false
  Explanation:It is not possible to get non-decreasing order for the given
              array by performing any number of right shift operations.

  */
const moveOneBall = (arr) => {

  if (arr.length == 0) { return true }
  let k = 0
  let len = arr.length
  for (let i = 0; i < len; i++) {
    let t = 1;
    for (let j = 1; j < len; j++) {
      if (arr[j] < arr[j - 1]) {
        t = 0;
        break;
      }
    }
    if (t == 1) {
      k = 1;
      break;
    }
    arr.push(arr[0]);
    arr.shift()
  }
  if (k == 1) { return true }
  return false
}

const testMoveOneBall = () => {
  console.assert(moveOneBall([3, 4, 5, 1, 2]) === true)
  console.assert(moveOneBall([3, 5, 10, 1, 2]) === true)
  console.assert(moveOneBall([4, 3, 1, 2]) === false)
  console.assert(moveOneBall([3, 5, 4, 1, 2]) === false)
  console.assert(moveOneBall([]) === true)
}

testMoveOneBall()


Prompt:
/*In this problem, you will implement a function that takes two lists of numbers,
  and determines whether it is possible to perform an exchange of elements
  between them to make lst1 a list of only even numbers.
  There is no limit on the number of exchanged elements between lst1 and lst2.
  If it is possible to exchange elements between the lst1 and lst2 to make
  all the elements of lst1 to be even, return "YES".
  Otherwise, return "NO".
  For example:
  exchange([1, 2, 3, 4], [1, 2, 3, 4]) => "YES"
  exchange([1, 2, 3, 4], [1, 5, 3, 4]) => "NO"
  It is assumed that the input lists will be non-empty.
  */
const exchange = (lst1, lst2) => {

  let k = lst1.length
  let t = 0
  for (let i = 0; i < lst1.length; i++) {
    if (lst1[i] % 2 == 0) { t++ }
  }
  for (let i = 0; i < lst2.length; i++) {
    if (lst2[i] % 2 == 0) { t++ }
  }
  if (t >= k) { return 'YES' }
  return 'NO'
}


Prompt:
/*Given a string representing a space separated lowercase letters, return a dictionary
  of the letter with the most repetition and containing the corresponding count.
  If several letters have the same occurrence, return all of them.

  Example:
  histogram('a b c') == {'a': 1, 'b': 1, 'c': 1}
  histogram('a b b a') == {'a': 2, 'b': 2}
  histogram('a b c a b') == {'a': 2, 'b': 2}
  histogram('b b b b a') == {'b': 4}
  histogram('') == {}

  */
const histogram = (test) => {

  let d = {}
  let t = test.split(/\s/)
  if (test == '') { t = [] }
  for (m in t) {
    if (t[m] in d) {
      d[t[m]]++
    }
    else {
      d[t[m]] = 1
    }
  }
  s = Object.keys(d).sort(function (a, b) { return - d[a] + d[b]; });
  if (s.length == 0) { return {} }
  let g = d[s[0]]
  let l = {}
  for (let ss=0; ss<s.length; ss++) {
    if (d[s[ss]] == g) {
      l[s[ss]] = d[s[ss]]
    }
  }
  return l
}

const testHistogram = () => {
  console.assert(
    JSON.stringify(histogram('a b b a')) === JSON.stringify({ a: 2, b: 2 })
  )
  console.assert(
    JSON.stringify(histogram('a b c a b')) === JSON.stringify({ a: 2, b: 2 })
  )
  console.assert(
    JSON.stringify(histogram('a b c d g')) ===
    JSON.stringify({ a: 1, b: 1, c: 1, d: 1, g: 1 })
  )
  console.assert(
    JSON.stringify(histogram('r t g')) === JSON.stringify({ r: 1, t: 1, g: 1 })
  )
  console.assert(
    JSON.stringify(histogram('b b b b a')) === JSON.stringify({ b: 4 })
  )
  console.assert(
    JSON.stringify(histogram('r t g')) === JSON.stringify({ r: 1, t: 1, g: 1 })
  )
  console.assert(JSON.stringify(histogram('')) === JSON.stringify({}))
  console.assert(JSON.stringify(histogram('a')) === JSON.stringify({ a: 1 }))
}

testHistogram()

'a b b a'
'a b c a b'
'a b c d g'
'r t g'
'b b b b a'
'r t g'
''
'a'


Prompt:
/*Task
  We are given two strings s and c, you have to deleted all the characters in s that are equal to any character in c
  then check if the result string is palindrome.
  A string is called palindrome if it reads the same backward as forward.
  You should return a tuple containing the result string and true/false for the check.
  Example
  For s = "abcde", c = "ae", the result should be ('bcd',false)
  For s = "abcdef", c = "b"  the result should be ('acdef',false)
  For s = "abcdedcba", c = "ab", the result should be ('cdedc',true)
  */
const reverseDelete = (s, c) => {

  let t = ''
  for (let i = 0; i < s.length; i++) {
    let y = 1
    for (let j = 0; j < c.length; j++) {
      if (s[i] == c[j]) {
        y = 0
      }
    }
    if (y == 1) {
      t += s[i]
    }
  }
  let z = 1
  for (let i = 0; i < t.length; i++) {
    if (t[i] != t[t.length - i - 1]) {
      z = 0
    }
  }
  if (z == 0) {
    return (z, false)
  }
  return (z, true)
}

const testReverseDelete = () => {
  console.assert(JSON.stringify(reverseDelete('abcde', 'ae')) ===
    JSON.stringify(['bcd', false]))
  console.assert(JSON.stringify(reverseDelete('abcdef', 'b')) ===
    JSON.stringify(['acdef', false]))
  console.assert(JSON.stringify(reverseDelete('abcdedcba', 'ab')) ===
    JSON.stringify(['cdedc', true]))
  console.assert(JSON.stringify(reverseDelete('dwik', 'w')) ===
    JSON.stringify(['dik', false]))
  console.assert(JSON.stringify(reverseDelete('a', 'a')) ===
    JSON.stringify(['', true]))
  console.assert(JSON.stringify(reverseDelete('abcdedcba', '')) ===
    JSON.stringify(['abcdedcba', true]))
  console.assert(JSON.stringify(reverseDelete('abcdedcba', 'v')) ===
    JSON.stringify(['abcdedcba', true]))
  console.assert(JSON.stringify(reverseDelete('vabba', 'v')) ===
    JSON.stringify(['abba', true]))
  console.assert(JSON.stringify(reverseDelete('mamma', 'mia')) ===
    JSON.stringify(['', true]))
}

testReverseDelete()

'abcde', 'ae'
'abcdef', 'b'
'abcdedcba', 'ab'
'dwik', 'w'
'a', 'a'
'abcdedcba', ''
'abcdedcba', 'v'
'vabba', 'v'
'mamma', 'mia'

['bcd', false]
['acdef', false]
['cdedc', true]
['dik', false]
['', true]
['abcdedcba', true]
['abcdedcba', true]
['abba', true]
['', true]


Prompt:
/*Given a list of strings, where each string consists of only digits, return a list.
  Each element i of the output should be "the number of odd elements in the
  string i of the input." where all the i's should be replaced by the number
  of odd digits in the i'th string of the input.

  >>> oddCount(['1234567'])
  ["the number of odd elements 4n the str4ng 4 of the 4nput."]
  >>> oddCount(['3',"11111111"])
  ["the number of odd elements 1n the str1ng 1 of the 1nput.",
   "the number of odd elements 8n the str8ng 8 of the 8nput."]
  */
const oddCount = (lst) => {

  let d = []
  for (let i = 0; i < lst.length; i++) {
    let p = 0;
    let h = lst[i].length
    for (let j = 0; j < h; j++) {
      if (lst[i][j].charCodeAt() % 2 == 1) { p++ }
    }
    p = p.toString()
    d.push('the number of odd elements ' + p + 'n the str' + p + 'ng ' + p + ' of the ' + p + 'nput.')
  }
  return d
}

const testOddCount = () => {
  console.assert(
    JSON.stringify(oddCount(['1234567'])) ===
    JSON.stringify([
      'the number of odd elements 4n the str4ng 4 of the 4nput.',
    ])
  )
  console.assert(JSON.stringify(
    oddCount(['3', '11111111'])) ===
    JSON.stringify([
      'the number of odd elements 1n the str1ng 1 of the 1nput.',
      'the number of odd elements 8n the str8ng 8 of the 8nput.',
    ])
  )
  console.assert(
    JSON.stringify(oddCount(['271', '137', '314'])) ===
    JSON.stringify([
      'the number of odd elements 2n the str2ng 2 of the 2nput.',
      'the number of odd elements 3n the str3ng 3 of the 3nput.',
      'the number of odd elements 2n the str2ng 2 of the 2nput.',
    ])
  )
}

testOddCount()


Prompt:
/*
  Given an array of integers nums, find the minimum sum of any non-empty sub-array
  of nums.
  Example
  minSubArraySum([2, 3, 4, 1, 2, 4]) == 1
  minSubArraySum([-1, -2, -3]) == -6
  */
const minSubArraySum = (nums) => {

  let min = nums[0]
  for (let i = 0; i < nums.length; i++) {
    for (let j = i + 1; j <= nums.length; j++) {
      let s = 0;
      for (let k = i; k < j; k++) {
        s += nums[k]
      }
      if (s < min) { min = s }
    }
  }
  return min
}

const testMinSubArraySum = () => {
  console.assert(minSubArraySum([2, 3, 4, 1, 2, 4]) === 1)
  console.assert(minSubArraySum([-1, -2, -3]) === -6)
  console.assert(minSubArraySum([-1, -2, -3, 2, -10]) === -14)
  console.assert(minSubArraySum([-9999999999999999]) === -9999999999999999)
  console.assert(minSubArraySum([0, 10, 20, 1000000]) === 0)
  console.assert(minSubArraySum([-1, -2, -3, 10, -5]) === -6)
  console.assert(minSubArraySum([100, -1, -2, -3, 10, -5]) === -6)
  console.assert(minSubArraySum([10, 11, 13, 8, 3, 4]) === 3)
  console.assert(minSubArraySum([100, -33, 32, -1, 0, -2]) === -33)
  console.assert(minSubArraySum([-10]) === -10)
  console.assert(minSubArraySum([7]) === 7)
  console.assert(minSubArraySum([1, -1]) === -1)
}

testMinSubArraySum()


Prompt:
/*
  You are given a rectangular grid of wells. Each row represents a single well,
  and each 1 in a row represents a single unit of water.
  Each well has a corresponding bucket that can be used to extract water from it,
  and all buckets have the same capacity.
  Your task is to use the buckets to empty the wells.
  Output the number of times you need to lower the buckets.

  Example 1:
      Input:
          grid : [[0,0,1,0], [0,1,0,0], [1,1,1,1]]
          bucket_capacity : 1
      Output: 6

  Example 2:
      Input:
          grid : [[0,0,1,1], [0,0,0,0], [1,1,1,1], [0,1,1,1]]
          bucket_capacity : 2
      Output: 5

  Example 3:
      Input:
          grid : [[0,0,0], [0,0,0]]
          bucket_capacity : 5
      Output: 0

  Constraints:
      * all wells have the same length
      * 1 <= grid.length <= 10^2
      * 1 <= grid[:,1].length <= 10^2
      * grid[i][j] -> 0 | 1
      * 1 <= capacity <= 10
  */
const maxFill = (grid, capacity) => {

  let p = 0
  for (let i = 0; i < grid.length; i++) {
    let m = 0
    for (let j = 0; j < grid[i].length; j++) {
      if (grid[i][j] == 1) { m++ }
    }
    while (m > 0) {
      m -= capacity;
      p++;
    }
  }
  return p
}


Prompt:
/*
  In this Kata, you have to sort an array of non-negative integers according to
  number of ones in their binary representation in ascending order.
  For similar number of ones, sort based on decimal value.

  It must be implemented like this:
  >>> sortArray([1, 5, 2, 3, 4]) == [1, 2, 3, 4, 5]
  >>> sortArray([-2, -3, -4, -5, -6]) == [-6, -5, -4, -3, -2]
  >>> sortArray([1, 0, 2, 3, 4]) [0, 1, 2, 3, 4]
  */
const sortArray = (arr) => {

  let p = arr
  for (let j = 0; j < p.length; j++) {
    let ind = j
    for (let k = j + 1; k < p.length; k++) {
      let w1 = p[ind].toString(2)
      let f1 = 0
      for (let u = 0; u < w1.length; u++) {
        if (w1[u] == '1') { f1++ }
      }
      let w2 = p[k].toString(2)
      let f2 = 0
      for (let u = 0; u < w2.length; u++) {
        if (w2[u] == '1') { f2++ }
      }
      if (f2 < f1 || (f1 == f2 && p[k] < p[ind])) {
        ind = k
      }
    }
    if (ind > j) {
      let tmp = p[j]
      p[j] = p[ind]
      p[ind] = tmp
    }
  }
  return p
}

const testSortArray = () => {
  console.assert(
    JSON.stringify(sortArray([1, 5, 2, 3, 4])) ===
    JSON.stringify([1, 2, 4, 3, 5])
  )

  console.assert(
    JSON.stringify(sortArray([-2, -3, -4, -5, -6])) ===
    JSON.stringify([-4, -2, -6, -5, -3])
  )
  console.assert(
    JSON.stringify(sortArray([1, 0, 2, 3, 4])) ===
    JSON.stringify([0, 1, 2, 4, 3])
  )
  console.assert(JSON.stringify(sortArray([])) === JSON.stringify([]))
  console.assert(
    JSON.stringify(sortArray([2, 5, 77, 4, 5, 3, 5, 7, 2, 3, 4])) ===
    JSON.stringify([2, 2, 4, 4, 3, 3, 5, 5, 5, 7, 77])
  )
  console.assert(
    JSON.stringify(sortArray([3, 6, 44, 12, 32, 5])) ===
    JSON.stringify([32, 3, 5, 6, 12, 44])
  )
  console.assert(
    JSON.stringify(sortArray([2, 4, 8, 16, 32])) ===
    JSON.stringify([2, 4, 8, 16, 32])
  )
  console.assert(
    JSON.stringify(sortArray([2, 4, 8, 16, 32])) ===
    JSON.stringify([2, 4, 8, 16, 32])
  )
}

testSortArray()


Prompt:
/*Given a string s and a natural number n, you have been tasked to implement
  a function that returns a list of all words from string s that contain exactly
  n consonants, in order these words appear in the string s.
  If the string s is empty then the function should return an empty list.
  Note: you may assume the input string contains only letters and spaces.
  Examples:
  selectWords("Mary had a little lamb", 4) ==> ["little"]
  selectWords("Mary had a little lamb", 3) ==> ["Mary")
  selectWords("simple white space", 2) ==> []
  selectWords("Hello world", 4) ==> ["world"]
  selectWords("Uncle sam", 3) ==> ["Uncle"]
  */
const selectWords = (s, n) => {

const testSelectWords = () => {
  console.assert(
    JSON.stringify(selectWords('Mary had a little lamb', 4)) ===
    JSON.stringify(['little'])
  )
  console.assert(
    JSON.stringify(selectWords('simple white space', 2)) === JSON.stringify([])
  )
  console.assert(
    JSON.stringify(selectWords('Hello world', 4)) === JSON.stringify(['world'])
  )
  console.assert(
    JSON.stringify(selectWords('Uncle sam', 3)) === JSON.stringify(['Uncle'])
  )

  console.assert(
    JSON.stringify(selectWords('a b c d e f', 1)) ===
    JSON.stringify(['b', 'c', 'd', 'f'])
  )

  console.assert(
    JSON.stringify(selectWords('Mary had a little lamb', 3)) ===
    JSON.stringify(['Mary', 'lamb'])
  )
  console.assert(JSON.stringify(selectWords('', 4)) === JSON.stringify([]))
}

testSelectWords()

'Mary had a little lamb', 4
'simple white space', 2
'Hello world', 4
'Uncle sam', 3
'a b c d e f', 1
'Mary had a little lamb', 3
'', 4


Prompt:
/*You are given a word. Your task is to find the closest vowel that stands between
  two consonants from the right side of the word (case sensitive).

  Vowels in the beginning and ending doesn't count. Return empty string if you didn't
  find any vowel met the above condition.

  You may assume that the given string contains English letter only.

  Example:
  getClosestVowel("yogurt") ==> "u"
  getClosestVowel("FULL") ==> "U"
  getClosestVowel("quick") ==> ""
  getClosestVowel("ab") ==> ""
  */
const getClosestVowel = (word) => {

const testGetClosestVowel = () => {
  console.assert(getClosestVowel('yogurt') === 'u')
  console.assert(getClosestVowel('full') === 'u')
  console.assert(getClosestVowel('easy') === '')
  console.assert(getClosestVowel('eAsy') === '')
  console.assert(getClosestVowel('ali') === '')
  console.assert(getClosestVowel('bad') === 'a')
  console.assert(getClosestVowel('most') === 'o')
  console.assert(getClosestVowel('ab') === '')
  console.assert(getClosestVowel('ba') === '')
  console.assert(getClosestVowel('quick') === '')
  console.assert(getClosestVowel('anime') === 'i')
  console.assert(getClosestVowel('Asia') === '')
  console.assert(getClosestVowel('Above') === 'o')
}

testGetClosestVowel()

'yogurt' 'full' 'easy' 'eAsy' 'ali' 'bad' 'most' 'ab' 'ba' 'quick' 'anime' 'Asia' 'Above'


Prompt:
/* You are given a list of two strings, both strings consist of open
  parentheses '(' or close parentheses ')' only.
  Your job is to check if it is possible to concatenate the two strings in
  some order, that the resulting string will be good.
  A string S is considered to be good if and only if all parentheses in S
  are balanced. For example: the string '(())()' is good, while the string
  '())' is not.
  Return 'Yes' if there's a way to make a good string, and return 'No' otherwise.
  Examples:
  matchParens(['()(', ')']) == 'Yes'
  matchParens([')', ')']) == 'No'
  */
const matchParens = (lst) => {

const testMatchParens = () => {
  console.assert(matchParens(['()(', ')']) === 'Yes')
  console.assert(matchParens([')', ')']) === 'No')
  console.assert(matchParens(['(()(())', '())())']) === 'No')
  console.assert(matchParens([')())', '(()()(']) === 'Yes')
  console.assert(matchParens(['(())))', '(()())((']) === 'Yes')
  console.assert(matchParens(['()', '())']) === 'No')
  console.assert(matchParens(['(()(', '()))()']) === 'Yes')
  console.assert(matchParens(['((((', '((())']) === 'No')
  console.assert(matchParens([')(()', '(()(']) === 'No')
  console.assert(matchParens([')(', ')(']) === 'No')
  console.assert(matchParens(['(', ')']) === 'Yes')
  console.assert(matchParens([')', '(']) === 'Yes')
}
testMatchParens()

'Yes' 'No' 'No' 'Yes' 'Yes' 'No' 'Yes' 'No' 'No' 'No' 'Yes' 'Yes'


Prompt:
/*
  Given an array arr of integers and a positive integer k, return a sorted list
  of length k with the maximum k numbers in arr.

  Example 1:

      Input: arr = [-3, -4, 5], k = 3
      Output: [-4, -3, 5]

  Example 2:

      Input: arr = [4, -4, 4], k = 2
      Output: [4, 4]

  Example 3:

      Input: arr = [-3, 2, 1, 2, -1, -2, 1], k = 1
      Output: [2]

  Note:
      1. The length of the array will be in the range of [1, 1000].
      2. The elements in the array will be in the range of [-1000, 1000].
      3. 0 <= k <= len(arr)
  */
const maximum = (arr, k) => {

  let p = arr
  for (let j = 0; j < p.length; j++) {
    let ind = j
    for (let k = j + 1; k < p.length; k++) {
      if (p[k] < p[ind]) {
        ind = k
      }
    }
    if (ind > j) {
      let tmp = p[j]
      p[j] = p[ind]
      p[ind] = tmp
    }
  }
  if (k == 0) { return [] }
  return p.slice(-k)
}

const testMaximum = () => {
  console.assert(
    JSON.stringify(maximum([-3, -4, 5], 3)) === JSON.stringify([-4, -3, 5])
  )
  console.assert(
    JSON.stringify(maximum([4, -4, 4], 2)) === JSON.stringify([4, 4])
  )
  console.assert(
    JSON.stringify(maximum([-3, 2, 1, 2, -1, -2, 1], 1)) === JSON.stringify([2])
  )
  console.assert(
    JSON.stringify(maximum([123, -123, 20, 0, 1, 2, -3], 3)) ===
    JSON.stringify([2, 20, 123])
  )
  console.assert(
    JSON.stringify(maximum([-123, 20, 0, 1, 2, -3], 4)) ===
    JSON.stringify([0, 1, 2, 20])
  )
  console.assert(
    JSON.stringify(maximum([5, 15, 0, 3, -13, -8, 0], 7)) ===
    JSON.stringify([-13, -8, 0, 0, 3, 5, 15])
  )
  console.assert(
    JSON.stringify(maximum([-1, 0, 2, 5, 3, -10], 2)) === JSON.stringify([3, 5])
  )
  console.assert(
    JSON.stringify(maximum([1, 0, 5, -7], 1)) === JSON.stringify([5])
  )
  console.assert(JSON.stringify(maximum([4, -4], 2)) === JSON.stringify([-4, 4]))
  console.assert(
    JSON.stringify(maximum([-10, 10], 2)) === JSON.stringify([-10, 10])
  )
  console.assert(
    JSON.stringify(maximum([1, 2, 3, -23, 243, -400, 0], 0)) ===
    JSON.stringify([])
  )
}

testMaximum()


Prompt:
/*Given a non-empty list of integers, return the sum of all of the odd elements that are in even positions.

  Examples
  solution([5, 8, 7, 1]) ==> 12
  solution([3, 3, 3, 3, 3]) ==> 9
  solution([30, 13, 24, 321]) ==>0
  */
const solution = (lst) => {

  let p = 0
  for (let i = 0; i < lst.length; i += 2) {
    if (lst[i] % 2 == 1) {
      p += lst[i]
    }
  }
  return p
}

const testSolution = () => {
  console.assert(solution([5, 8, 7, 1]) === 12)
  console.assert(solution([3, 3, 3, 3, 3]) === 9)
  console.assert(solution([30, 13, 24, 321]) === 0)
  console.assert(solution([5, 9]) === 5)
  console.assert(solution([2, 4, 8]) === 0)
  console.assert(solution([30, 13, 23, 32]) === 23)
  console.assert(solution([3, 13, 2, 9]) === 3)
}

testSolution()


Prompt:
/*
  Given a non-empty array of integers arr and an integer k, return
  the sum of the elements with at most two digits from the first k elements of arr.

  Example:

      Input: arr = [111,21,3,4000,5,6,7,8,9], k = 4
      Output: 24 # sum of 21 + 3

  Constraints:
      1. 1 <= len(arr) <= 100
      2. 1 <= k <= len(arr)
  */
const addElements = (arr, k) => {


Prompt:
/*
  Given a positive integer n, return a sorted list that has the odd numbers in collatz sequence.

  The Collatz conjecture is a conjecture in mathematics that concerns a sequence defined
  as follows: start with any positive integer n. Then each term is obtained from the
  previous term as follows: if the previous term is even, the next term is one half of
  the previous term. If the previous term is odd, the next term is 3 times the previous
  term plus 1. The conjecture is that no matter what value of n, the sequence will always reach 1.

  Note:
      1. Collatz(1) is [1].
      2. returned list sorted in increasing order.

  For example:
  getOddCollatz(5) returns [1, 5] # The collatz sequence for 5 is [5, 16, 8, 4, 2, 1], so the odd numbers are only 1, and 5.
  */
const getOddCollatz = (n) => {

  let p = []
  let t = n
  while (1) {
    let u = 0
    for (let i = 0; i < p.length; i++) {
      if (t == p[i]) {
        u = 1
        break;
      }
    }
    if (u == 1) { break }
    if (t % 2 == 1) { p.push(t); t = 3 * t + 1 }
    else { t = t / 2 }
  }
  for (let j = 0; j < p.length; j++) {
    let ind = j
    for (let k = j + 1; k < p.length; k++) {
      if (p[k] < p[ind]) {
        ind = k
      }
    }
    if (ind > j) {
      let tmp = p[j]
      p[j] = p[ind]
      p[ind] = tmp
    }
  }
  return p
}

const testGetOddCollatz = () => {
  console.assert(
    JSON.stringify(getOddCollatz(14)) === JSON.stringify([1, 5, 7, 11, 13, 17])
  )
  console.assert(JSON.stringify(getOddCollatz(5)) === JSON.stringify([1, 5]))
  console.assert(JSON.stringify(getOddCollatz(12)) === JSON.stringify([1, 3, 5]))
  console.assert(JSON.stringify(getOddCollatz(1)) === JSON.stringify([1]))
}

testGetOddCollatz()


Prompt:
/*You have to write a function which validates a given date string and
  returns true if the date is valid otherwise false.
  The date is valid if all of the following rules are satisfied:
  1. The date string is not empty.
  2. The number of days is not less than 1 or higher than 31 days for months 1,3,5,7,8,10,12. And the number of days is not less than 1 or higher than 30 days for months 4,6,9,11. And, the number of days is not less than 1 or higher than 29 for the month 2.
  3. The months should not be less than 1 or higher than 12.
  4. The date should be in the format: mm-dd-yyyy

  for example:
  validDate('03-11-2000') => true

  validDate('15-01-2012') => false

  validDate('04-0-2040') => false

  validDate('06-04-2020') => true

  validDate('06/04/2020') => false
  */
const validDate = (date) => {

const testValidDate = () => {
  console.assert(validDate('03-11-2000') === true)
  console.assert(validDate('15-01-2012') === false)
  console.assert(validDate('04-0-2040') === false)
  console.assert(validDate('06-04-2020') === true)
  console.assert(validDate('01-01-2007') === true)
  console.assert(validDate('03-32-2011') === false)
  console.assert(validDate('') === false)
  console.assert(validDate('04-31-3000') === false)
  console.assert(validDate('06-06-2005') === true)
  console.assert(validDate('21-31-2000') === false)
  console.assert(validDate('04-12-2003') === true)
  console.assert(validDate('04122003') === false)
  console.assert(validDate('20030412') === false)
  console.assert(validDate('2003-04') === false)
  console.assert(validDate('2003-04-12') === false)
  console.assert(validDate('04-2003') === false)
}

testValidDate()

true false false true true false false false true false true false false false false false


Prompt:
/* Given a string of words, return a list of words split on whitespace, if no whitespaces exists in the text you
  should split on commas ',' if no commas exists you should return the number of lower-case letters with odd order in the
  alphabet, ord('a') = 0, ord('b') = 1, ... ord('z') = 25
  Examples
  splitWords("Hello world!") ➞ ["Hello", "world!"]
  splitWords("Hello,world!") ➞ ["Hello", "world!"]
  splitWords("abcdef") == 3
  */
const splitWords = (txt) => {

  let t = txt.split(/\s/)
  if (t.length > 1) {
    return t
  } else {
    t = txt.split(/,/)
    if (t.length > 1) {
      return t
    } else {
      let p = 0
      for (let i = 0; i < txt.length; i++) {
        let m = txt[i].charCodeAt()
        if (m >= 97 && m <= 122 && m % 2 == 0) {
          p++
        }
      }
      return p
    }
  }
}

const testSplitWords = () => {
  console.assert(
    JSON.stringify(splitWords('Hello world!')) ===
    JSON.stringify(['Hello', 'world!'])
  )
  console.assert(
    JSON.stringify(splitWords('Hello,world!')) ===
    JSON.stringify(['Hello', 'world!'])
  )
  console.assert(
    JSON.stringify(splitWords('Hello world,!')) ===
    JSON.stringify(['Hello', 'world,!'])
  )
  console.assert(
    JSON.stringify(splitWords('Hello,Hello,world !')) ===
    JSON.stringify(['Hello,Hello,world', '!'])
  )
  console.assert(JSON.stringify(splitWords('abcdef')) === JSON.stringify(3))
  console.assert(JSON.stringify(splitWords('aaabb')) === JSON.stringify(2))
  console.assert(JSON.stringify(splitWords('aaaBb')) === JSON.stringify(1))
  console.assert(JSON.stringify(splitWords('')) === JSON.stringify(0))
}

testSplitWords()

'Hello world!'
'Hello,world!'
'Hello world,!'
'Hello,Hello,world !'
'abcdef'
'aaabb'
'aaaBb'
''


Prompt:
/* Given a list of numbers, return whether or not they are sorted
  in ascending order. If list has more than 1 duplicate of the same
  number, return false. Assume no negative numbers and only integers.
  Examples
  isSorted([5]) ➞ true
  isSorted([1, 2, 3, 4, 5]) ➞ true
  isSorted([1, 3, 2, 4, 5]) ➞ false
  isSorted([1, 2, 3, 4, 5, 6]) ➞ true
  isSorted([1, 2, 3, 4, 5, 6, 7]) ➞ true
  isSorted([1, 3, 2, 4, 5, 6, 7]) ➞ false
  isSorted([1, 2, 2, 3, 3, 4]) ➞ true
  isSorted([1, 2, 2, 2, 3, 4]) ➞ false
  */
const isSorted = (lst) => {

  if (lst.length == 0) { return true }
  let dup = 1
  let pre = lst[0]
  for (let i = 1; i < lst.length; i++) {
    if (lst[i] < pre) { return false }
    if (lst[i] == pre) {
      dup += 1;
      if (dup == 3) { return false }
    } else {
      pre = lst[i]
      dup = 1
    }
  }
  return true
}

const testIsSorted = () => {
  console.assert(isSorted([5]) === true)
  console.assert(isSorted([1, 2, 3, 4, 5]) === true)
  console.assert(isSorted([1, 3, 2, 4, 5]) === false)
  console.assert(isSorted([1, 2, 3, 4, 5, 6]) === true)
  console.assert(isSorted([1, 2, 3, 4, 5, 6, 7]) === true)
  console.assert(isSorted([1, 3, 2, 4, 5, 6, 7]) === false)
  console.assert(isSorted([]) === true)
  console.assert(isSorted([1]) === true)
  console.assert(isSorted([3, 2, 1]) === false)
  console.assert(isSorted([1, 2, 2, 2, 3, 4]) === false)
  console.assert(isSorted([1, 2, 3, 3, 3, 4]) === false)
  console.assert(isSorted([1, 2, 2, 3, 3, 4]) === true)
  console.assert(isSorted([1, 2, 3, 4]) === true)
}

testIsSorted()

true true false true true false true true false false false true true


Prompt:
/*You are given two intervals,
  where each interval is a pair of integers. For example, interval = (start, end) = (1, 2).
  The given intervals are closed which means that the interval (start, end)
  includes both start and end.
  For each given interval, it is assumed that its start is less or equal its end.
  Your task is to determine whether the length of intersection of these two
  intervals is a prime number.
  Example, the intersection of the intervals (1, 3), (2, 4) is (2, 3)
  which its length is 1, which not a prime number.
  If the length of the intersection is a prime number, return "YES",
  otherwise, return "NO".
  If the two intervals don't intersect, return "NO".

  [input/output] samples:
  intersection((1, 2), (2, 3)) ==> "NO"
  intersection((-1, 1), (0, 4)) ==> "NO"
  intersection((-3, -1), (-5, 5)) ==> "YES"
  */
const intersection = (interval1, interval2) => {

  let lo = interval1[0]
  if (interval2[0] > lo) { lo = interval2[0] }
  let hi = interval1[1]
  if (interval2[1] < hi) { hi = interval2[1] }
  let len = 0
  if (hi > lo) { len = hi - lo }
  if (len == 1 || len == 0) { return 'NO' }
  for (let i = 2; i * i <= len; i++) {
    if (len % i == 0) { return 'NO' }
  }
  return 'YES'
}

const testIntersection = () => {
  console.assert(intersection([1, 2], [2, 3]) === 'NO')
  console.assert(intersection([-1, 1], [0, 4]) === 'NO')
  console.assert(intersection([-3, -1], [-5, 5]) === 'YES')
  console.assert(intersection([-2, 2], [-4, 0]) === 'YES')
  console.assert(intersection([-11, 2], [-1, -1]) === 'NO')
  console.assert(intersection([1, 2], [3, 5]) === 'NO')
  console.assert(intersection([1, 2], [1, 2]) === 'NO')
  console.assert(intersection([-2, -2], [-3, -2]) === 'NO')
}

testIntersection()

'NO' 'NO' 'YES' 'YES' 'NO' 'NO' 'NO' 'NO'


Prompt:
/*
  You are given an array arr of integers and you need to return
  sum of magnitudes of integers multiplied by product of all signs
  of each number in the array, represented by 1, -1 or 0.
  Note: return null for empty arr.

  Example:
  >>> prodSigns([1, 2, 2, -4]) == -9
  >>> prodSigns([0, 1]) == 0
  >>> prodSigns([]) == null
  */
const prodSigns = (arr) => {

  if (arr.length == 0) { return null }
  let n = 1
  let s = 0
  for (let i = 0; i < arr.length; i++) {
    s += arr[i]
    if (arr[i] == 0) { return 0 }
    if (arr[i] < 0) { n = -n; s -= 2 * arr[i] }
  }
  return s * n
}

const testProdSigns = () => {
  console.assert(prodSigns([1, 2, 2, -4]) === -9)
  console.assert(prodSigns([0, 1]) === 0)
  console.assert(prodSigns([1, 1, 1, 2, 3, -1, 1]) === -10)
  console.assert(prodSigns([]) === null)
  console.assert(prodSigns([2, 4, 1, 2, -1, -1, 9]) === 20)
  console.assert(prodSigns([-1, 1, -1, 1]) === 4)
  console.assert(prodSigns([-1, 1, 1, 1]) === -4)
  console.assert(prodSigns([-1, 1, 1, 0]) === 0)
}

testProdSigns()


Prompt:
/*
  Given a grid with N rows and N columns (N >= 2) and a positive integer k,
  each cell of the grid contains a value. Every integer in the range [1, N * N]
  inclusive appears exactly once on the cells of the grid.

  You have to find the minimum path of length k in the grid. You can start
  from any cell, and in each step you can move to any of the neighbor cells,
  in other words, you can go to cells which share an edge with you current
  cell.
  Please note that a path of length k means visiting exactly k cells (not
  necessarily distinct).
  You CANNOT go off the grid.
  A path A (of length k) is considered less than a path B (of length k) if
  after making the ordered lists of the values on the cells that A and B go
  through (let's call them lst_A and lst_B), lst_A is lexicographically less
  than lst_B, in other words, there exist an integer index i (1 <= i <= k)
  such that lst_A[i] < lst_B[i] and for any j (1 <= j < i) we have
  lst_A[j] = lst_B[j].
  It is guaranteed that the answer is unique.
  Return an ordered list of the values on the cells that the minimum path go through.

  Examples:

      Input: grid = [ [1,2,3], [4,5,6], [7,8,9]], k = 3
      Output: [1, 2, 1]

      Input: grid = [ [5,9,3], [4,1,6], [7,8,2]], k = 1
      Output: [1]
  */
const minPath = (grid, k) => {

  let m = 0
  let n = 0
  for (let i = 0; i < grid.length; i++) {
    for (let j = 0; j < grid.length; j++) {
      if (grid[i][j] == 1) {
        m = i;
        n = j;
        break;
      }
    }
  }
  let min = grid.length * grid.length
  if (m > 0 && grid[m - 1][n] < min) { min = grid[m - 1][n] }
  if (n > 0 && grid[m][n - 1] < min) { min = grid[m][n - 1] }
  if (m < grid.length - 1 && grid[m + 1][n] < min) { min = grid[m + 1][n] }
  if (n < grid.length - 1 && grid[m][n + 1] < min) { min = grid[m][n + 1] }
  let p = []
  for (let i = 0; i < k; i++) {
    if (i % 2 == 0) { p.push(1) }
    else { p.push(min) }
  }
  return p
}


Prompt:
/*Everyone knows Fibonacci sequence, it was studied deeply by mathematicians in
  the last couple centuries. However, what people don't know is Tribonacci sequence.
  Tribonacci sequence is defined by the recurrence:
  tri(1) = 3
  tri(n) = 1 + n / 2, if n is even.
  tri(n) =  tri(n - 1) + tri(n - 2) + tri(n + 1), if n is odd.
  For example:
  tri(2) = 1 + (2 / 2) = 2
  tri(4) = 3
  tri(3) = tri(2) + tri(1) + tri(4)
         = 2 + 3 + 3 = 8
  You are given a non-negative integer number n, you have to a return a list of the
  first n + 1 numbers of the Tribonacci sequence.
  Examples:
  tri(3) = [1, 3, 2, 8]
  */
const tri = (n) => {


Prompt:
/*Given a positive integer n, return the product of the odd digits.
  Return 0 if all digits are even.
  For example:
  digits(1)  == 1
  digits(4)  == 0
  digits(235) == 15
  */
const digits = (n) => {

const testDigits = () => {
  console.assert(digits(5) === 5)
  console.assert(digits(54) === 5)
  console.assert(digits(120) === 1)
  console.assert(digits(5014) === 5)
  console.assert(digits(98765) === 315)
  console.assert(digits(5576543) === 2625)
  console.assert(digits(2468) === 0)
}

testDigits()


Prompt:
/*
  Create a function that takes a string as input which contains only square brackets.
  The function should return true if and only if there is a valid subsequence of brackets
  where at least one bracket in the subsequence is nested.
  isNested('[[]]') ➞ true
  isNested('[]]]]]]][[[[[]') ➞ false
  isNested('[][]') ➞ false
  isNested('[]') ➞ false
  isNested('[[][]]') ➞ true
  isNested('[[]][[') ➞ true
  */
const isNested = (string) => {

  let opening_bracket_index = []
  let closing_bracket_index1 = []
  for (let i = 0; i < string.length; i++) {
    if (string[i] == '[') {
      opening_bracket_index.push(i)
    }
    else {
      closing_bracket_index1.push(i)
    }
  }
  let closing_bracket_index = []
  for (let i = 0; i < closing_bracket_index1.length; i++) {
    closing_bracket_index.push(closing_bracket_index1[closing_bracket_index1.length - i - 1])
  }
  let cnt = 0
  let i = 0
  let l = closing_bracket_index.length
  for (let k = 0; k < opening_bracket_index.length; k++) {
    if (i < l && opening_bracket_index[k] < closing_bracket_index[i]) {
      cnt += 1;
      i += 1;
    }
  }
  return cnt >= 2
}

const testIsNested = () => {
  console.assert(isNested('[[]]') === true)
  console.assert(isNested('[]]]]]]][[[[[]') === false)
  console.assert(isNested('[][]') === false)
  console.assert(isNested('[]') === false)
  console.assert(isNested('[[[[]]]]') === true)
  console.assert(isNested('[]]]]]]]]]]') === false)
  console.assert(isNested('[][][[]]') === true)
  console.assert(isNested('[[]') === false)
  console.assert(isNested('[]]') === false)
  console.assert(isNested('[[]][[') === true)
  console.assert(isNested('[[][]]') === true)
  console.assert(isNested('') === false)
  console.assert(isNested('[[[[[[[[') === false)
  console.assert(isNested(']]]]]]]]') === false)
}

testIsNested()

true false false false true false true false false true true false false false


Prompt:
/*You are given a list of numbers.
  You need to return the sum of squared numbers in the given list,
  round each element in the list to the upper int(Ceiling) first.
  Examples:
  For lst = [1,2,3] the output should be 14
  For lst = [1,4,9] the output should be 98
  For lst = [1,3,5,7] the output should be 84
  For lst = [1.4,4.2,0] the output should be 29
  For lst = [-2.4,1,1] the output should be 6
  */
const sumSquares = (lst) => {

  let p = 0
  for (let i = 0; i < lst.length; i++) {
    let y = lst[i]
    if (y % 1 != 0) {
      if (y > 0) { y = y - y % 1 + 1 }
      else { y = -y; y = y - y % 1 }
    }
    p += y * y
  }
  return p
}

const testSumSquares = () => {
  console.assert(sumSquares([1, 2, 3]) === 14)
  console.assert(sumSquares([1.0, 2, 3]) === 14)
  console.assert(sumSquares([1, 3, 5, 7]) === 84)
  console.assert(sumSquares([1.4, 4.2, 0]) === 29)
  console.assert(sumSquares([-2.4, 1, 1]) === 6)

  console.assert(sumSquares([100, 1, 15, 2]) === 10230)
  console.assert(sumSquares([10000, 10000]) === 200000000)
  console.assert(sumSquares([-1.4, 4.6, 6.3]) === 75)
  console.assert(sumSquares([-1.4, 17.9, 18.9, 19.9]) === 1086)

  console.assert(sumSquares([0]) === 0)
  console.assert(sumSquares([-1]) === 1)
  console.assert(sumSquares([-1, 1, 0]) === 2)
}

testSumSquares()


Prompt:
/* Create a function that returns true if the last character
  of a given string is an alphabetical character and is not
  a part of a word, and false otherwise.
  Note: "word" is a group of characters separated by space.
  Examples:
  checkIfLastCharIsALetter("apple pie") ➞ false
  checkIfLastCharIsALetter("apple pi e") ➞ true
  checkIfLastCharIsALetter("apple pi e ") ➞ false
  checkIfLastCharIsALetter("") ➞ false
  */
const checkIfLastCharIsALetter = (txt) => {

  let len = txt.length
  if (len == 0) { return false }
  let y = txt[len - 1].charCodeAt()
  if (len == 1) {
    if ((y >= 65 && y <= 90) || (y >= 97 && y <= 122)) { return true }
    return false
  }
  if (txt[len - 2] == ' ' && ((y >= 65 && y <= 90) || (y >= 97 && y <= 122))) { return true }
  return false
}

const testCheckIfLastCharIsALetter = () => {
  console.assert(checkIfLastCharIsALetter('apple') === false)
  console.assert(checkIfLastCharIsALetter('apple pi e') === true)
  console.assert(checkIfLastCharIsALetter('eeeee') === false)
  console.assert(checkIfLastCharIsALetter('A') === true)
  console.assert(checkIfLastCharIsALetter('Pumpkin pie ') === false)
  console.assert(checkIfLastCharIsALetter('Pumpkin pie 1') === false)
  console.assert(checkIfLastCharIsALetter('') === false)
  console.assert(checkIfLastCharIsALetter('eeeee e ') === false)
  console.assert(checkIfLastCharIsALetter('apple pie') === false)
  console.assert(checkIfLastCharIsALetter('apple pi e ') === false)
}

testCheckIfLastCharIsALetter()

'apple'
'apple pi e'
'eeeee'
'A'
'Pumpkin pie '
'Pumpkin pie 1'
''
'eeeee e '
'apple pie'
'apple pi e '

false true false true false false false false false false


Prompt:
/*Create a function which returns the largest index of an element which
  is not greater than or equal to the element immediately preceding it. If
  no such element exists then return -1. The given array will not contain
  duplicate values.

  Examples:
  canArrange([1,2,4,3,5]) = 3
  canArrange([1,2,3]) = -1
  */
const canArrange = (arr) => {

  if (arr.length == 0) { return -1 }
  for (let i = arr.length - 1; i > 0; i--) {
    if (arr[i] < arr[i - 1]) { return i }
  }
  return -1
}

const testCanArrange = () => {
  console.assert(canArrange([1, 2, 4, 3, 5]) === 3)
  console.assert(canArrange([1, 2, 4, 5]) === -1)
  console.assert(canArrange([1, 4, 2, 5, 6, 7, 8, 9, 10]) === 2)
  console.assert(canArrange([4, 8, 5, 7, 3]) === 4)
  console.assert(canArrange([]) === -1)
}

testCanArrange()


Prompt:
/* Create a function that returns a list [a, b], where 'a' is
  the largest of negative integers, and 'b' is the smallest
  of positive integers in a list.
  If there is no negative or positive integers, return them as null.
  Examples:
  largestSmallestIntegers([2, 4, 1, 3, 5, 7]) == [null, 1]
  largestSmallestIntegers([]) == [null, null]
  largestSmallestIntegers([0]) == [null, null]
  */
const largestSmallestIntegers = (lst) => {

  let a = Infinity
  let b = -Infinity
  for (let i = 0; i < lst.length; i++) {
    if (lst[i] > 0 && lst[i] < a) { a = lst[i] }
    if (lst[i] < 0 && lst[i] > b) { b = lst[i] }
  }
  if (a == Infinity) { a = null }
  if (b == -Infinity) { b = null }
  return [b, a]
}

const testLargestSmallestIntegers = () => {
  console.assert(
    JSON.stringify(largestSmallestIntegers([2, 4, 1, 3, 5, 7])) ===
    JSON.stringify([null, 1])
  )
  console.assert(
    JSON.stringify(largestSmallestIntegers([2, 4, 1, 3, 5, 7, 0])) ===
    JSON.stringify([null, 1])
  )
  console.assert(
    JSON.stringify(largestSmallestIntegers([1, 3, 2, 4, 5, 6, -2])) ===
    JSON.stringify([-2, 1])
  )
  console.assert(
    JSON.stringify(largestSmallestIntegers([4, 5, 3, 6, 2, 7, -7])) ===
    JSON.stringify([-7, 2])
  )
  console.assert(
    JSON.stringify(largestSmallestIntegers([7, 3, 8, 4, 9, 2, 5, -9])) ===
    JSON.stringify([-9, 2])
  )
  console.assert(
    JSON.stringify(largestSmallestIntegers([])) === JSON.stringify([null, null])
  )
  console.assert(
    JSON.stringify(largestSmallestIntegers([0])) ===
    JSON.stringify([null, null])
  )
  console.assert(
    JSON.stringify(largestSmallestIntegers([-1, -3, -5, -6])) ===
    JSON.stringify([-1, null])
  )
  console.assert(
    JSON.stringify(largestSmallestIntegers([-1, -3, -5, -6, 0])) ===
    JSON.stringify([-1, null])
  )
  console.assert(
    JSON.stringify(largestSmallestIntegers([-6, -4, -4, -3, 1])) ===
    JSON.stringify([-3, 1])
  )
  console.assert(
    JSON.stringify(largestSmallestIntegers([-6, -4, -4, -3, -100, 1])) ===
    JSON.stringify([-3, 1])
  )
}

testLargestSmallestIntegers()


Prompt:
/*
  Create a function that takes integers, floats, or strings representing
  real numbers, and returns the larger variable in its given variable type.
  Return null if the values are equal.
  Note: If a real number is represented as a string, the floating point might be . or ,

  compareOne(1, 2.5) ➞ 2.5
  compareOne(1, "2,3") ➞ "2,3"
  compareOne("5,1", "6") ➞ "6"
  compareOne("1", 1) ➞ null
  */
const compareOne = (a, b) => {

  let aa = Number(a)
  if (typeof a == 'string') { aa = Number(a.replace(',', '.')) }
  let bb = Number(b)
  if (typeof b == 'string') { bb = Number(b.replace(',', '.')) }
  if (aa > bb) { return a }
  if (aa < bb) { return b }
  return null
}

const testCompareOne = () => {
  console.assert(compareOne(1, 2) === 2)
  console.assert(compareOne(1, 2.5) === 2.5)
  console.assert(compareOne(2, 3) === 3)
  console.assert(compareOne(5, 6) === 6)
  console.assert(compareOne(1, '2,3') === '2,3')
  console.assert(compareOne('5,1', '6') === '6')
  console.assert(compareOne('1', '2') === '2')
  console.assert(compareOne('1', 1) === null)
}

testCompareOne()


Prompt:
/*Evaluate whether the given number n can be written as the sum of exactly 4 positive even numbers
  Example
  isEqualToSumEven(4) == false
  isEqualToSumEven(6) == false
  isEqualToSumEven(8) == true
  */
const isEqualToSumEven = (n) => {

const testIsEqualToSumEven = () => {
  console.assert(isEqualToSumEven(4) === false)
  console.assert(isEqualToSumEven(6) === false)
  console.assert(isEqualToSumEven(8) === true)
  console.assert(isEqualToSumEven(10) === true)
  console.assert(isEqualToSumEven(11) === false)
  console.assert(isEqualToSumEven(12) === true)
  console.assert(isEqualToSumEven(13) === false)
  console.assert(isEqualToSumEven(16) === true)
}

testIsEqualToSumEven()

false false true true false true false true


Prompt:
/*The Brazilian factorial is defined as:
  brazilian_factorial(n) = n! * (n-1)! * (n-2)! * ... * 1!
  where n > 0

  For example:
  >>> specialFactorial(4)
  288

  The function will receive an integer as input and should return the special
  factorial of this integer.
  */
const specialFactorial = (n) => {

  let p = 1;
  let t = 1;
  while (n > 1) {
    let y = p;
    while (y > 0) {
      y--;
      t *= n;
    }
    p++;
    n--;
  }
  return t
}

const testSpecialFactorial = () => {
  console.assert(specialFactorial(4) === 288)
  console.assert(specialFactorial(5) === 34560)
  console.assert(specialFactorial(7) === 125411328000)
  console.assert(specialFactorial(1) === 1)
}

testSpecialFactorial()


Prompt:
/*
  Given a string text, replace all spaces in it with underscores,
  and if a string has more than 2 consecutive spaces,
  then replace all consecutive spaces with -

  fixSpaces("Example") == "Example"
  fixSpaces("Example 1") == "Example_1"
  fixSpaces(" Example 2") == "_Example_2"
  fixSpaces(" Example   3") == "_Example-3"
  */
const fixSpaces = (text) => {

const testFixSpaces = () => {
  console.assert(fixSpaces('Example') === 'Example')
  console.assert(fixSpaces('Mudasir Hanif ') === 'Mudasir_Hanif_')
  console.assert(
    fixSpaces('Yellow Yellow  Dirty  Fellow') === 'Yellow_Yellow__Dirty__Fellow'
  )
  console.assert(fixSpaces('Exa   mple') === 'Exa-mple')
  console.assert(fixSpaces('   Exa 1 2 2 mple') === '-Exa_1_2_2_mple')
}

testFixSpaces()

'Example'
'Mudasir Hanif '
'Yellow Yellow  Dirty  Fellow'
'Exa   mple'
'   Exa 1 2 2 mple'


Prompt:
/*Create a function which takes a string representing a file's name, and returns
  'Yes' if the the file's name is valid, and returns 'No' otherwise.
  A file's name is considered to be valid if and only if all the following conditions
  are met:
  - There should not be more than three digits ('0'-'9') in the file's name.
  - The file's name contains exactly one dot '.'
  - The substring before the dot should not be empty, and it starts with a letter from
  the latin alphapet ('a'-'z' and 'A'-'Z').
  - The substring after the dot should be one of these: ['txt', 'exe', 'dll']
  Examples:
  fileNameCheck("example.txt") # => 'Yes'
  fileNameCheck("1example.dll") # => 'No' (the name should start with a latin alphapet letter)
  */
const fileNameCheck = (file_name) => {

const testFileNameCheck = () => {
  console.assert(fileNameCheck('example.txt') === 'Yes')
  console.assert(fileNameCheck('1example.dll') === 'No')
  console.assert(fileNameCheck('s1sdf3.asd') === 'No')
  console.assert(fileNameCheck('K.dll') === 'Yes')
  console.assert(fileNameCheck('MY16FILE3.exe') === 'Yes')
  console.assert(fileNameCheck('His12FILE94.exe') === 'No')
  console.assert(fileNameCheck('_Y.txt') === 'No')
  console.assert(fileNameCheck('?aREYA.exe') === 'No')
  console.assert(fileNameCheck('/this_is_valid.dll') === 'No')
  console.assert(fileNameCheck('this_is_valid.wow') === 'No')
  console.assert(fileNameCheck('this_is_valid.txt') === 'Yes')
  console.assert(fileNameCheck('this_is_valid.txtexe') === 'No')
  console.assert(fileNameCheck('#this2_i4s_5valid.ten') === 'No')
  console.assert(fileNameCheck('@this1_is6_valid.exe') === 'No')
  console.assert(fileNameCheck('this_is_12valid.6exe4.txt') === 'No')
  console.assert(fileNameCheck('all.exe.txt') === 'No')
  console.assert(fileNameCheck('I563_No.exe') === 'Yes')
  console.assert(fileNameCheck('Is3youfault.txt') === 'Yes')
  console.assert(fileNameCheck('no_one#knows.dll') === 'Yes')
  console.assert(fileNameCheck('1I563_Yes3.exe') === 'No')
  console.assert(fileNameCheck('I563_Yes3.txtt') === 'No')
  console.assert(fileNameCheck('final..txt') === 'No')
  console.assert(fileNameCheck('final132') === 'No')
  console.assert(fileNameCheck('_f4indsartal132.') === 'No')
  console.assert(fileNameCheck('.txt') === 'No')
  console.assert(fileNameCheck('s.') === 'No')
}

testFileNameCheck()

'Yes' 'No' 'No' 'Yes' 'Yes' 'No' 'No' 'No' 'No' 'No' 'Yes' 'No' 'No' 'No' 'No' 'No' 'Yes' 'Yes' 'Yes' 'No' 'No' 'No' 'No' 'No' 'No' 'No'


Prompt:
/*"
  This function will take a list of integers. For all entries in the list, the function shall square the integer entry if its index is a
  multiple of 3 and will cube the integer entry if its index is a multiple of 4 and not a multiple of 3. The function will not
  change the entries in the list whose indexes are not a multiple of 3 or 4. The function shall then return the sum of all entries.

  Examples:
  For lst = [1,2,3] the output should be 6
  For lst = []  the output should be 0
  For lst = [-1,-5,2,-1,-5]  the output should be -126
  */
const sumSquares = (lst) => {

  let y = 0
  for (let i = 0; i < lst.length; i++) {
    if (i % 3 == 0) { y += lst[i] * lst[i] }
    else if (i % 4 == 0) { y += lst[i] * lst[i] * lst[i] }
    else { y += lst[i] }
  }
  return y
}


Prompt:
/*
  You are given a string representing a sentence,
  the sentence contains some words separated by a space,
  and you have to return a string that contains the words from the original sentence,
  whose lengths are prime numbers,
  the order of the words in the new string should be the same as the original one.

  Example 1:
      Input: sentence = "This is a test"
      Output: "is"

  Example 2:
      Input: sentence = "lets go for swimming"
      Output: "go for"

  Constraints:
      * 1 <= len(sentence) <= 100
      * sentence contains only letters
  */
const wordsInSentence = (sentence) => {

  let t = sentence.split(/\s/)
  let p = ''
  for (let j = 0; j < t.length; j++) {
    let len = t[j].length;
    let u = 1
    if (len == 1 || len == 0) { continue }
    for (let i = 2; i * i <= len; i++) {
      if (len % i == 0) { u = 0 }
    }
    if (u == 0) { continue }
    if (p == '') { p += t[j] }
    else { p = p + ' ' + t[j] }
  }
  return p
}

const testWordsInSentence = () => {
  console.assert(wordsInSentence('This is a test') === 'is')
  console.assert(wordsInSentence('lets go for swimming') === 'go for')
  console.assert(
    wordsInSentence('there is no place available here') === 'there is no place'
  )
  console.assert(wordsInSentence('Hi I am Hussein') === 'Hi am Hussein')
  console.assert(wordsInSentence('go for it') === 'go for it')
  console.assert(wordsInSentence('here') === '')
  console.assert(wordsInSentence('here is') === 'is')
}

testWordsInSentence()

'This is a test'
'lets go for swimming'
'there is no place available here'
'Hi I am Hussein'
'go for it'
'here'
'here is'

'is'
'go for'
'there is no place'
'Hi am Hussein'
'go for it'
''
'is'


Prompt:
/*Your task is to implement a function that will simplify the expression
  x * n. The function returns true if x * n evaluates to a whole number and false
  otherwise. Both x and n, are string representation of a fraction, and have the following format,
  <numerator>/<denominator> where both numerator and denominator are positive whole numbers.

  You can assume that x, and n are valid fractions, and do not have zero as denominator.

  simplify("1/5", "5/1") = true
  simplify("1/6", "2/1") = false
  simplify("7/10", "10/2") = false
  */
const simplify = (x, n) => {

  let a = x.split(/\//)
  let b = n.split(/\//)
  let m = Number(a[0]) * Number(b[0])
  let r = Number(a[1]) * Number(b[1])
  return m % r == 0
}

const testSimplify = () => {
  console.assert(simplify('1/5', '5/1') === true)
  console.assert(simplify('1/6', '2/1') === false)
  console.assert(simplify('5/1', '3/1') === true)
  console.assert(simplify('7/10', '10/2') === false)
  console.assert(simplify('2/10', '50/10') === true)
  console.assert(simplify('7/2', '4/2') === true)
  console.assert(simplify('11/6', '6/1') === true)
  console.assert(simplify('2/3', '5/2') === false)
  console.assert(simplify('5/2', '3/5') === false)
  console.assert(simplify('2/4', '8/4') === true)
  console.assert(simplify('2/4', '4/2') === true)
  console.assert(simplify('1/5', '5/1') === true)
  console.assert(simplify('1/5', '1/5') === false)
}

testSimplify()

true false true false true true true false false true true true false


Prompt:
/*
  Write a function which sorts the given list of integers
  in ascending order according to the sum of their digits.
  Note: if there are several items with similar sum of their digits,
  order them based on their index in original list.

  For example:
  >>> orderByPoints([1, 11, -1, -11, -12]) == [-1, -11, 1, -12, 11]
  >>> orderByPoints([]) == []
  */
const orderByPoints = (nums) => {


Prompt:
/*Write a function that takes an array of numbers as input and returns
  the number of elements in the array that are greater than 10 and both
  first and last digits of a number are odd (1, 3, 5, 7, 9).
  For example:
  specialFilter([15, -73, 14, -15]) => 1
  specialFilter([33, -2, -3, 45, 21, 109]) => 2
  */
const specialFilter = (nums) => {

  let p = 0
  for (let i = 0; i < nums.length; i++) {
    if (nums[i] < 10) { continue }
    let y = nums[i].toString()
    if (Number(y[0]) % 2 == 1 && Number(y[y.length - 1]) % 2 == 1) {
      p++
    }
  }
  return p
}

const testSpecialFilter = () => {
  console.assert(specialFilter([5, -2, 1, -5]) === 0)
  console.assert(specialFilter([15, -73, 14, -15]) === 1)
  console.assert(specialFilter([33, -2, -3, 45, 21, 109]) === 2)
  console.assert(specialFilter([43, -12, 93, 125, 121, 109]) === 4)
  console.assert(specialFilter([71, -2, -33, 75, 21, 19]) === 3)
  console.assert(specialFilter([1]) === 0)
  console.assert(specialFilter([]) === 0)
}

testSpecialFilter()


Prompt:
/*
  You are given a positive integer n. You have to create an integer array a of length n.
      For each i (1 ≤ i ≤ n), the value of a[i] = i * i - i + 1.
      Return the number of triples (a[i], a[j], a[k]) of a where i < j < k,
  and a[i] + a[j] + a[k] is a multiple of 3.

  Example :
      Input: n = 5
      Output: 1
      Explanation:
      a = [1, 3, 7, 13, 21]
      The only valid triple is (1, 7, 13).
  */
const getMaxTriples = (n) => {

const testGetMaxTriples = () => {
  console.assert(getMaxTriples(5) === 1)
  console.assert(getMaxTriples(6) === 4)
  console.assert(getMaxTriples(10) === 36)
  console.assert(getMaxTriples(100) === 53361)
}

testGetMaxTriples()


Prompt:
/* There are eight planets in our solar system: the closerst to the Sun
  is Mercury, the next one is Venus, then Earth, Mars, Jupiter, Saturn,
  Uranus, Neptune.
  Write a function that takes two planet names as strings planet1 and planet2.
  The function should return a tuple containing all planets whose orbits are
  located between the orbit of planet1 and the orbit of planet2, sorted by
  the proximity to the sun.
  The function should return an empty tuple if planet1 or planet2
  are not correct planet names.
  Examples
  bf("Jupiter", "Neptune") ==> ("Saturn", "Uranus")
  bf("Earth", "Mercury") ==> ("Venus")
  bf("Mercury", "Uranus") ==> ("Venus", "Earth", "Mars", "Jupiter", "Saturn")
  */
const bf = (planet1, planet2) => {

  let y = ['Mercury', 'Venus', 'Earth', 'Mars', 'Jupiter', 'Saturn', 'Uranus', 'Neptune']
  let u = []
  let lo = -1
  let hi = -1
  for (let i = 0; i < 8; i++) {
    if (y[i] == planet1) { lo = i }
  }
  for (let i = 0; i < 8; i++) {
    if (y[i] == planet2) { hi = i }
  }
  if (lo == -1 || hi == -1 || lo == hi) { return [] }
  if (lo > hi) {
    let tmp = lo;
    lo = hi;
    hi = tmp;
  }
  for (let i = lo + 1; i < hi; i++) {
    u.push(y[i])
  }
  return u
}

const testBf = () => {
  console.assert(
    JSON.stringify(bf('Jupiter', 'Neptune')) ===
    JSON.stringify(['Saturn', 'Uranus'])
  )
  console.assert(
    JSON.stringify(bf('Earth', 'Mercury')) === JSON.stringify(['Venus'])
  )
  console.assert(
    JSON.stringify(bf('Mercury', 'Uranus')) ===
    JSON.stringify(['Venus', 'Earth', 'Mars', 'Jupiter', 'Saturn'])
  )
  console.assert(
    JSON.stringify(bf('Neptune', 'Venus')) ===
    JSON.stringify(['Earth', 'Mars', 'Jupiter', 'Saturn', 'Uranus'])
  )
  console.assert(JSON.stringify(bf('Earth', 'Earth')) === JSON.stringify([]))
  console.assert(JSON.stringify(bf('Mars', 'Earth')) === JSON.stringify([]))
  console.assert(
    JSON.stringify(bf('Jupiter', 'Makemake')) === JSON.stringify([])
  )
}

testBf()

'Jupiter', 'Neptune'
'Earth', 'Mercury'
'Mercury', 'Uranus'
'Neptune', 'Venus'
'Earth', 'Earth'
'Mars', 'Earth'
'Jupiter', 'Makemake'


Prompt:
/*Write a function that accepts a list of strings as a parameter,
  deletes the strings that have odd lengths from it,
  and returns the resulted list with a sorted order,
  The list is always a list of strings and never an array of numbers,
  and it may contain duplicates.
  The order of the list should be ascending by length of each word, and you
  should return the list sorted by that rule.
  If two words have the same length, sort the list alphabetically.
  The function should return a list of strings in sorted order.
  You may assume that all words will have the same length.
  For example:
  assert list_sort(["aa", "a", "aaa"]) => ["aa"]
  assert list_sort(["ab", "a", "aaa", "cd"]) => ["ab", "cd"]
  */
const sortedListSum = (lst) => {

  let p = []
  for (let i = 0; i < lst.length; i++) {
    if (lst[i].length % 2 == 0) {
      p.push(lst[i])
    }
  }
  for (let j = p.length - 2; j >= 0; j--) {
    for (let k = 0; k <= j; k++) {
      let f = 0
      if (p[k].length > p[k + 1].length) { f = 1 }
      if (p[k].length == p[k + 1].length) {
        let r = p[k].length
        for (let l = 0; l < r; l++) {
          if (p[k][l].charCodeAt() > p[k + 1][l].charCodeAt()) {
            f = 1;
            break;
          }
          if (p[k][l].charCodeAt() < p[k + 1][l].charCodeAt()) {
            break;
          }
        }
      }
      if (f == 1) {
        let tmp = p[k]
        p[k] = p[k + 1]
        p[k + 1] = tmp
      }
    }
  }
  return p
}

const testSortedListSum = () => {
  console.assert(
    JSON.stringify(sortedListSum(['aa', 'a', 'aaa'])) === JSON.stringify(['aa'])
  )
  console.assert(
    JSON.stringify(sortedListSum(['school', 'AI', 'asdf', 'b'])) ===
    JSON.stringify(['AI', 'asdf', 'school'])
  )
  console.assert(
    JSON.stringify(sortedListSum(['d', 'b', 'c', 'a'])) === JSON.stringify([])
  )
  console.assert(
    JSON.stringify(sortedListSum(['d', 'dcba', 'abcd', 'a'])) ===
    JSON.stringify(['abcd', 'dcba'])
  )
  console.assert(
    JSON.stringify(sortedListSum(['AI', 'ai', 'au'])) ===
    JSON.stringify(['AI', 'ai', 'au'])
  )
  console.assert(
    JSON.stringify(sortedListSum(['a', 'b', 'b', 'c', 'c', 'a'])) ===
    JSON.stringify([])
  )
  console.assert(
    JSON.stringify(sortedListSum(['aaaa', 'bbbb', 'dd', 'cc'])) ===
    JSON.stringify(['cc', 'dd', 'aaaa', 'bbbb'])
  )
}

testSortedListSum()


Prompt:
/*A simple program which should return the value of x if n is
  a prime number and should return the value of y otherwise.

  Examples:
  for xOrY(7, 34, 12) == 34
  for xOrY(15, 8, 5) == 5

  */
const xOrY = (n, x, y) => {

  let len = n
  if (len == 1 || len == 0) { return y }
  for (let i = 2; i * i <= len; i++) {
    if (len % i == 0) { return y }
  }
  return x
}

const testXOrY = () => {
  console.assert(xOrY(7, 34, 12) === 34)
  console.assert(xOrY(15, 8, 5) === 5)
  console.assert(xOrY(3, 33, 5212) === 33)
  console.assert(xOrY(1259, 3, 52) === 3)
  console.assert(xOrY(7919, -1, 12) === -1)
  console.assert(xOrY(3609, 1245, 583) === 583)
  console.assert(xOrY(91, 56, 129) === 129)
  console.assert(xOrY(6, 34, 1234) === 1234)
  console.assert(xOrY(1, 2, 0) === 0)
  console.assert(xOrY(2, 2, 0) === 2)
}

testXOrY()


Prompt:
/* Given a list of numbers, return the sum of squares of the numbers
  in the list that are odd. Ignore numbers that are negative or not integers.
  doubleTheDifference([1, 3, 2, 0]) == 1 + 9 + 0 + 0 = 10
  doubleTheDifference([-1, -2, 0]) == 0
  doubleTheDifference([9, -2]) == 81
  doubleTheDifference([0]) == 0
  If the input list is empty, return 0.
  */
const doubleTheDifference = (lst) => {

  let p = 0
  for (let i = 0; i < lst.length; i++) {
    if (lst[i] % 2 == 1 && lst[i] > 0) {
      p += lst[i] * lst[i]
    }
  }
  return p
}

const testDoubleTheDifference = () => {
  console.assert(doubleTheDifference([]) === 0)
  console.assert(doubleTheDifference([5, 4]) === 25)
  console.assert(doubleTheDifference([0.1, 0.2, 0.3]) === 0)
  console.assert(doubleTheDifference([-10, -20, -30]) === 0)
  console.assert(doubleTheDifference([-1, -2, 8]) === 0)
  console.assert(doubleTheDifference([0.2, 3, 5]) === 34)
  let lst = []
  let odd_sum = 0
  for (let i = -99; i < 100; i += 2) {
    if (i % 2 != 0 && i > 0) { odd_sum += i * i }
    lst.push(i)
  }
  console.assert(doubleTheDifference(lst) === odd_sum)
}
testDoubleTheDifference()


Prompt:
/*I think we all remember that feeling when the result of some long-awaited
  event is finally known. The feelings and thoughts you have at that moment are
  definitely worth noting down and comparing.
  Your task is to determine if a person correctly guessed the results of a number of matches.
  You are given two arrays of scores and guesses of equal length, where each index shows a match.
  Return an array of the same length denoting how far off each guess was. If they have guessed correctly,
  the value is 0, and if not, the value is the absolute difference between the guess and the score.

  example:

  compare([1,2,3,4,5,1],[1,2,3,4,2,-2]) -> [0,0,0,0,3,3]
  compare([0,5,0,0,0,4],[4,1,1,0,0,-2]) -> [4,4,1,0,0,6]
  */
const compare = (game, guess) => {

  for (let i = 0; i < guess.length; i++) {
    game[i] -= guess[i]
 if (game[i]<0)
 game[i]=-game[i];  }
  return game
}


Prompt:
/*You will be given the name of a class (a string) and a list of extensions.
  The extensions are to be used to load additional classes to the class. The
  strength of the extension is as follows: Let CAP be the number of the uppercase
  letters in the extension's name, and let SM be the number of lowercase letters
  in the extension's name, the strength is given by the fraction CAP - SM.
  You should find the strongest extension and return a string in this
  format: ClassName.StrongestExtensionName.
  If there are two or more extensions with the same strength, you should
  choose the one that comes first in the list.
  For example, if you are given "Slices" as the class and a list of the
  extensions: ['SErviNGSliCes', 'Cheese', 'StuFfed'] then you should
  return 'Slices.SErviNGSliCes' since 'SErviNGSliCes' is the strongest extension
  (its strength is -1).
  Example:
  for strongestExtension('my_class', ['AA', 'Be', 'CC']) == 'my_class.AA'
  */
const strongestExtension = (class_name, extensions) => {

  let u = 0
  let s = -Infinity
  for (let i = extensions.length - 1; i >= 0; i--) {
    let y = 0
    for (let j = 0; j < extensions[i].length; j++) {
      let k = extensions[i][j].charCodeAt()
      if (k >= 65 && k <= 90) { y += 1 }
      if (k >= 97 && k <= 122) { y -= 1 }
    }
    if (y >= s) {
      s = y;
      u = i;
    }
  }
  return class_name + '.' + extensions[u]
}

const testStrongestExtension = () => {
  console.assert(
    strongestExtension('Watashi', ['tEN', 'niNE', 'eIGHt8OKe']) ===
    'Watashi.eIGHt8OKe')
  console.assert(
    strongestExtension('Boku123', [
      'nani',
      'NazeDa',
      'YEs.WeCaNe',
      '32145tggg',
    ]) === 'Boku123.YEs.WeCaNe')
  console.assert(
    strongestExtension('__YESIMHERE', [
      't',
      'eMptY',
      'nothing',
      'zeR00',
      'NuLl__',
      '123NoooneB321',
    ]) === '__YESIMHERE.NuLl__')
  console.assert(
    strongestExtension('K', ['Ta', 'TAR', 't234An', 'cosSo']) === 'K.TAR')
  console.assert(
    strongestExtension('__HAHA', ['Tab', '123', '781345', '-_-']) ===
    '__HAHA.123')
  console.assert(
    strongestExtension('YameRore', [
      'HhAas',
      'okIWILL123',
      'WorkOut',
      'Fails',
      '-_-',
    ]) === 'YameRore.okIWILL123')
  console.assert(
    strongestExtension('finNNalLLly', ['Die', 'NowW', 'Wow', 'WoW']) ===
    'finNNalLLly.WoW')
  console.assert(strongestExtension('_', ['Bb', '91245']) === '_.Bb')
  console.assert(strongestExtension('Sp', ['671235', 'Bb']) === 'Sp.671235')
}

testStrongestExtension()


Prompt:
/*You are given 2 words. You need to return true if the second word or any of its rotations is a substring in the first word
  cycpatternCheck("abcd","abd") => false
  cycpatternCheck("hello","ell") => true
  cycpatternCheck("whassup","psus") => false
  cycpatternCheck("abab","baa") => true
  cycpatternCheck("efef","eeff") => false
  cycpatternCheck("himenss","simen") => true
  */
const cycpatternCheck = (a, b) => {

  let l = b.length
  let pat = b + b
  for (let i = 0; i < a.length - l + 1; i++) {
    for (let j = 0; j < l + 1; j++) {
      let y = 1
      for (let k = 0; k < l; k++) {
        if (a[i + k] != pat[j + k]) { y = 0 }
      }
      if (y == 1) {
        return true
      }
    }
  }
  return false
}

const testCycpatternCheck = () => {
  console.assert(cycpatternCheck('xyzw', 'xyw') === false)
  console.assert(cycpatternCheck('yello', 'ell') === true)
  console.assert(cycpatternCheck('whattup', 'ptut') === false)
  console.assert(cycpatternCheck('efef', 'fee') === true)
  console.assert(cycpatternCheck('abab', 'aabb') === false)
  console.assert(cycpatternCheck('winemtt', 'tinem') === true)
}

testCycpatternCheck()

'xyzw', 'xyw'
'yello', 'ell'
'whattup', 'ptut'
'efef', 'fee'
'abab', 'aabb'
'winemtt', 'tinem'


Prompt:
/*Given an integer. return a list that has the number of even and odd digits respectively.

   Example:
      evenOddCount(-12) ==> [1, 1]
      evenOddCount(123) ==> [1, 2]
  */
const evenOddCount = (num) => {

  let o = 0
  let e = 0
  if (num < 0) { num = -num }
  while (num > 0) {
    if (num % 2 == 0) { e++ }
    else { o++ }
    num = (num - num % 10) / 10
  }
  return [e, o]
}

const testEvenOddCount = () => {
  console.assert(JSON.stringify(evenOddCount(7)) === JSON.stringify([0, 1]))
  console.assert(JSON.stringify(evenOddCount(-78)) === JSON.stringify([1, 1]))
  console.assert(JSON.stringify(evenOddCount(3452)) === JSON.stringify([2, 2]))
  console.assert(
    JSON.stringify(evenOddCount(346211)) === JSON.stringify([3, 3])
  )
  console.assert(
    JSON.stringify(evenOddCount(-345821)) === JSON.stringify([3, 3])
  )
  console.assert(JSON.stringify(evenOddCount(-2)) === JSON.stringify([1, 0]))
  console.assert(
    JSON.stringify(evenOddCount(-45347)) === JSON.stringify([2, 3])
  )
  console.assert(JSON.stringify(evenOddCount(0)) === JSON.stringify([1, 0]))
}

testEvenOddCount()


Prompt:
/*
  Given a positive integer, obtain its roman numeral equivalent as a string,
  and return it in lowercase.
  Restrictions: 1 <= num <= 1000

  Examples:
  >>> intToMiniRoman(19) == 'xix'
  >>> intToMiniRoman(152) == 'clii'
  >>> intToMiniRoman(426) == 'cdxxvi'
  */
const intToMiniRoman = (number) => {

const testIntToMiniRoman = () => {
  console.assert(intToMiniRoman(19) === 'xix')
  console.assert(intToMiniRoman(152) === 'clii')
  console.assert(intToMiniRoman(251) === 'ccli')
  console.assert(intToMiniRoman(426) === 'cdxxvi')
  console.assert(intToMiniRoman(500) === 'd')
  console.assert(intToMiniRoman(1) === 'i')
  console.assert(intToMiniRoman(4) === 'iv')
  console.assert(intToMiniRoman(43) === 'xliii')
  console.assert(intToMiniRoman(90) === 'xc')
  console.assert(intToMiniRoman(94) === 'xciv')
  console.assert(intToMiniRoman(532) === 'dxxxii')
  console.assert(intToMiniRoman(900) === 'cm')
  console.assert(intToMiniRoman(994) === 'cmxciv')
  console.assert(intToMiniRoman(1000) === 'm')
}

testIntToMiniRoman()

'xix' 'clii' 'ccli' 'cdxxvi' 'd' 'i' 'iv' 'xliii' 'xc' 'xciv' 'dxxxii' 'cm' 'cmxciv' 'm'


Prompt:
/*
 Given the lengths of the three sides of a triangle. Return true if the three
  sides form a right-angled triangle, false otherwise.
  A right-angled triangle is a triangle in which one angle is right angle or
  90 degree.
  Example:
  rightAngleTriangle(3, 4, 5) == true
  rightAngleTriangle(1, 2, 3) == false
  */
const rightAngleTriangle = (a, b, c) => {

const testRightAngleTriangle = () => {
  console.assert(rightAngleTriangle(3, 4, 5) === true)
  console.assert(rightAngleTriangle(1, 2, 3) === false)
  console.assert(rightAngleTriangle(10, 6, 8) === true)
  console.assert(rightAngleTriangle(2, 2, 2) === false)
  console.assert(rightAngleTriangle(7, 24, 25) === true)
  console.assert(rightAngleTriangle(10, 5, 7) === false)
  console.assert(rightAngleTriangle(5, 12, 13) === true)
  console.assert(rightAngleTriangle(15, 8, 17) === true)
  console.assert(rightAngleTriangle(48, 55, 73) === true)
  console.assert(rightAngleTriangle(1, 1, 1) === false)
  console.assert(rightAngleTriangle(2, 2, 10) === false)
}

testRightAngleTriangle()

true false true false true false true true true false false


Prompt:
/*Write a function that accepts a list of strings.
  The list contains different words. Return the word with maximum number
  of unique characters. If multiple strings have maximum number of unique
  characters, return the one which comes first in lexicographical order.

  findMax(["name", "of", "string"]) === "string"
  findMax(["name", "enam", "game"]) === "enam"
  findMax(["aaaaaaa", "bb" ,"cc"]) === ""aaaaaaa"
  */
const findMax = (words) => {

  let s = -1
  let u = -1
  if (words.length == 0) { return '' }
  for (let i = 0; i < words.length; i++) {
    let p = 0
    for (let j = 0; j < words[i].length; j++) {
      let y = 1
      for (let k = 0; k < j; k++) {
        if (words[i][j] == words[i][k]) { y = 0 }
      }
      if (y == 1) { p++ }
    }
    if (p > s || (p == s && words[i] < words[u])) {
      u = i;
      s = p;
    }
  }
  return words[u]
}

const testFindMax = () => {
  console.assert(findMax(['name', 'of', 'string']) === 'string')
  console.assert(findMax(['name', 'enam', 'game']) === 'enam')
  console.assert(findMax(['aaaaaaa', 'bb', 'cc']) === 'aaaaaaa')
  console.assert(findMax(['abc', 'cba']) === 'abc')
  console.assert(
    findMax(['play', 'this', 'game', 'of', 'footbott']) === 'footbott')
  console.assert(findMax(['we', 'are', 'gonna', 'rock']) === 'gonna')
  console.assert(findMax(['we', 'are', 'a', 'mad', 'nation']) === 'nation')
  console.assert(findMax(['this', 'is', 'a', 'prrk']) === 'this')
  console.assert(findMax(['b']) === 'b')
  console.assert(findMax(['play', 'play', 'play']) === 'play')
}

testFindMax()

'string' 'enam' 'aaaaaaa' 'abc' 'footbott' 'gonna' 'nation' 'this' 'b' 'play'


Prompt:
/*
  You're a hungry rabbit, and you already have eaten a certain number of carrots,
  but now you need to eat more carrots to complete the day's meals.
  you should return an array of [ total number of eaten carrots after your meals,
                                  the number of carrots left after your meals ]
  if there are not enough remaining carrots, you will eat all remaining carrots, but will still be hungry.

  Example:
  * eat(5, 6, 10) -> [11, 4]
  * eat(4, 8, 9) -> [12, 1]
  * eat(1, 10, 10) -> [11, 0]
  * eat(2, 11, 5) -> [7, 0]

  Variables:
  @number : integer
      the number of carrots that you have eaten.
  @need : integer
      the number of carrots that you need to eat.
  @remaining : integer
      the number of remaining carrots thet exist in stock

  Constrain:
  * 0 <= number <= 1000
  * 0 <= need <= 1000
  * 0 <= remaining <= 1000

  Have fun :)
  */
const eat = (number, need, remaining) => {

  if (need <= remaining) {
    return [need + number, remaining - need]
  }
  return [remaining + number, 0]
}

const testEat = () => {
  console.assert(JSON.stringify(eat(5, 6, 10)) === JSON.stringify([11, 4]))
  console.assert(JSON.stringify(eat(4, 8, 9)) === JSON.stringify([12, 1]))
  console.assert(JSON.stringify(eat(1, 10, 10)) === JSON.stringify([11, 0]))
  console.assert(JSON.stringify(eat(2, 11, 5)) === JSON.stringify([7, 0]))
  console.assert(JSON.stringify(eat(4, 5, 7)) === JSON.stringify([9, 2]))
  console.assert(JSON.stringify(eat(4, 5, 1)) === JSON.stringify([5, 0]))
}

testEat()


Prompt:
/*
  Given two lists operator, and operand. The first list has basic algebra operations, and
  the second list is a list of integers. Use the two given lists to build the algebric
  expression and return the evaluation of this expression.

  The basic algebra operations:
  Addition ( + )
  Subtraction ( - )
  Multiplication ( * )
  Floor division ( // )
  Exponentiation ( ** )

  Example:
  operator['+', '*', '-']
  array = [2, 3, 4, 5]
  result = 2 + 3 * 4 - 5
  => result = 9

  Note:
      The length of operator list is equal to the length of operand list minus one.
      Operand is a list of of non-negative integers.
      Operator list has at least one operator, and operand list has at least two operands.

  */
const doAlgebra = (operator, operand) => {

  while (operator.length > 0) {
    let y = 0
    for (let i = operator.length - 1; i >= 0; i--) {
      if (operator[i] == '**') {
        let u = operand[i]
        while (operand[i + 1] > 1) {
          operand[i + 1]--;
          operand[i] *= u;
        }
        operand.splice(i + 1, 1)
        operator.splice(i, 1)
        y = 1;
        break;
      }
    }
    if (y == 1) { continue }
    for (let i = 0; i < operator.length; i++) {
      if (operator[i] == '*') {
        operand[i] *= operand[i + 1]
        operand.splice(i + 1, 1)
        operator.splice(i, 1)
        y = 1;
        break;
      }
      else if (operator[i] == '//') {
        operand[i] = (operand[i] - operand[i] % operand[i + 1]) / operand[i + 1]
        operand.splice(i + 1, 1)
        operator.splice(i, 1)
        y = 1;
        break;
      }
    }
    if (y == 1) { continue }
    for (let i = 0; i < operator.length; i++) {
      if (operator[i] == '+') {
        operand[i] += operand[i + 1]
        operand.splice(i + 1, 1)
        operator.splice(i, 1)
        y = 1;
        break;
      }
      else if (operator[i] == '-') {
        operand[i] -= operand[i + 1]
        operand.splice(i + 1, 1)
        operator.splice(i, 1)
        y = 1;
        break;
      }
    }
    if (y == 1) { continue }
  }
  return operand[0]
}


Prompt:
/*You are given a string s.
  if s[i] is a letter, reverse its case from lower to upper or vise versa,
  otherwise keep it as it is.
  If the string contains no letters, reverse the string.
  The function should return the resulted string.
  Examples
  solve("1234") = "4321"
  solve("ab") = "AB"
  solve("#a@C") = "#A@c"
  */
const solve = (s) => {

  let t = 0
  let p = ''
  for (let i = 0; i < s.length; i++) {
    let y = s[i].charCodeAt()
    if (y >= 65 && y <= 90) {
      y += 32;
      t = 1;
    } else if (y >= 97 && y <= 122) {
      y -= 32;
      t = 1;
    }
    p += String.fromCharCode(y)
  }
  if (t == 1) { return p }
  let u = ''
  for (let i = 0; i < p.length; i++) {
    u += p[p.length - i - 1]
  }
  return u
}

const testSolve = () => {
  console.assert(solve('AsDf') === 'aSdF')
  console.assert(solve('1234') === '4321')
  console.assert(solve('ab') === 'AB')
  console.assert(solve('#a@C') === '#A@c')
  console.assert(solve('#AsdfW^45') === '#aSDFw^45')
  console.assert(solve('#6@2') === '2@6#')
  console.assert(solve('#$a^D') === '#$A^d')
  console.assert(solve('#ccc') === '#CCC')
}

testSolve()


Prompt:
/*
  Given a string 'text', return its md5 hash equivalent string.
  If 'text' is an empty string, return null.

  >>> stringToMd5('Hello world') == '3e25960a79dbc69b674cd4ec67a72c62'
  */
const stringToMd5 = (text) => {

  if (text == '') { return null }
  var md5 = require('js-md5')
  return md5(text)
}

const testStringToMd5 = () => {
  console.assert(
    stringToMd5('Hello world') === '3e25960a79dbc69b674cd4ec67a72c62')
  console.assert(stringToMd5('') === null)
  console.assert(stringToMd5('A B C') === '0ef78513b0cb8cef12743f5aeb35f888')
  console.assert(stringToMd5('password') === '5f4dcc3b5aa765d61d8327deb882cf99')
}

testStringToMd5()


Prompt:
/*
  Given two positive integers a and b, return the even digits between a
  and b, in ascending order.

  For example:
  generateIntegers(2, 8) => [2, 4, 6, 8]
  generateIntegers(8, 2) => [2, 4, 6, 8]
  generateIntegers(10, 14) => []
  */
const generateIntegers = (a, b) => {

  if (a > b) {
    let tmp = a;
    a = b;
    b = tmp;
  }
  let y = []
  for (let i = a; i <= b; i++) {
    if (i == 2 || i == 4 || i == 6 || i == 8) { y.push(i) }
  }
  return y
}

const testGenerateIntegers = () => {
  console.assert(
    JSON.stringify(generateIntegers(2, 10)) === JSON.stringify([2, 4, 6, 8])
  )
  console.assert(
    JSON.stringify(generateIntegers(10, 2)) === JSON.stringify([2, 4, 6, 8])
  )
  console.assert(
    JSON.stringify(generateIntegers(132, 2)) === JSON.stringify([2, 4, 6, 8])
  )
  console.assert(
    JSON.stringify(generateIntegers(17, 89)) === JSON.stringify([])
  )
}

testGenerateIntegers()