Prompt:
/* Check if in given list of numbers, are any two numbers closer to each other than
  given threshold.
  >>> hasCloseElements([1.0, 2.0, 3.0], 0.5)
  false
  >>> hasCloseElements([1.0, 2.8, 3.0, 4.0, 5.0, 2.0], 0.3)
  true
  */
const hasCloseElements = (numbers, threshold) => {

  for (let i = 0; i < numbers.length; i++) {
    for (let j = 0; j < numbers.length; j++) {
      if (i != j) {
        let distance = Math.abs(numbers[i] - numbers[j]);
        if (distance < threshold) {
          return true;
        }
      }
    }
  }
  return false;
}

const testHasCloseElements = () => {
  console.assert(hasCloseElements([1.0, 2.0, 3.9, 4.0, 5.0, 2.2], 0.3) === true)
  console.assert(
    hasCloseElements([1.0, 2.0, 3.9, 4.0, 5.0, 2.2], 0.05) === false
  )
  console.assert(hasCloseElements([1.0, 2.0, 5.9, 4.0, 5.0], 0.95) === true)
  console.assert(hasCloseElements([1.0, 2.0, 5.9, 4.0, 5.0], 0.8) === false)
  console.assert(hasCloseElements([1.0, 2.0, 3.0, 4.0, 5.0, 2.0], 0.1) === true)
  console.assert(hasCloseElements([1.1, 2.2, 3.1, 4.1, 5.1], 1.0) === true)
  console.assert(hasCloseElements([1.1, 2.2, 3.1, 4.1, 5.1], 0.5) === false)
}

testHasCloseElements()

const testHasCloseElements = () => {
  console.assert(hasCloseElements([1.0, 2.0, 3.0], 0.5) === false)
  console.assert(
    hasCloseElements([1.0, 2.8, 3.0, 4.0, 5.0, 2.0], 0.3) === true
  )
}
testHasCloseElements()


Prompt:
/* Input to this function is a string containing multiple groups of nested parentheses. Your goal is to
  separate those group into separate strings and return the list of those.
  Separate groups are balanced (each open brace is properly closed) and not nested within each other
  Ignore any spaces in the input string.
  >>> separateParenGroups('( ) (( )) (( )( ))')
  ['()', '(())', '(()())']
  */
const separateParenGroups = (paren_string) => {

  var result = [];
  var current_string = [];
  var current_depth = 0;

  for (const c of paren_string) {
    if (c == '(') {
      current_depth += 1;
      current_string.push(c);
    } else if (c == ')') {
      current_depth -= 1;
      current_string.push(c);
      if (current_depth == 0) {
        result.push(current_string.join(''));
        current_string = [];
      }
    }
  }

  return result;
}

const testSeparateParenGroups = () => {
  console.assert(
    JSON.stringify(separateParenGroups('(()()) ((())) () ((())()())')) ===
      JSON.stringify(['(()())', '((()))', '()', '((())()())'])
  )
  console.assert(
    JSON.stringify(separateParenGroups('() (()) ((())) (((())))')) ===
      JSON.stringify(['()', '(())', '((()))', '(((())))'])
  )
  console.assert(
    JSON.stringify(separateParenGroups('(()(())((())))')) ===
      JSON.stringify(['(()(())((())))'])
  )
  console.assert(
    JSON.stringify(separateParenGroups('( ) (( )) (( )( ))')) ===
      JSON.stringify(['()', '(())', '(()())'])
  )
}

testSeparateParenGroups()

const testSeparateParenGroups = () => {
  console.assert(
    JSON.stringify(separateParenGroups('( ) (( )) (( )( ))')) ===
      JSON.stringify(['()', '(())', '(()())'])
  )
}
testSeparateParenGroups()


Prompt:
/* Given a positive floating point number, it can be decomposed into
  and integer part (largest integer smaller than given number) and decimals
  (leftover part always smaller than 1).

  Return the decimal part of the number.
  >>> truncateNumber(3.5)
  0.5
  */
const truncateNumber = (number) => {

const testTruncateNumber = () => {
  console.assert(truncateNumber(3.5) === 0.5)

  console.assert(Math.abs(truncateNumber(1.33) - 0.33) < 1e-6)

  console.assert(Math.abs(truncateNumber(123.456 - 0.456) < 1e-6))
}

testTruncateNumber()

const testTruncateNumber = () => {
  console.assert(truncateNumber(3.5) === 0.5)
}
testTruncateNumber()


Prompt:
/* You're given a list of deposit and withdrawal operations on a bank account that starts with
  zero balance. Your task is to detect if at any point the balance of account fallls below zero, and
  at that point function should return true. Otherwise it should return false.
  >>> belowZero([1, 2, 3])
  false
  >>> belowZero([1, 2, -4, 5])
  true
  */
const belowZero = (operations) => {

  var balance = 0;
  for (const op of operations) {
    balance += op;
    if (balance < 0) {
      return true;
    }
  }
  return false;
}

const testBelowZero = () => {
  console.assert(belowZero([]) === false)
  console.assert(belowZero([1, 2, -3, 1, 2, -3]) === false)
  console.assert(belowZero([1, 2, -4, 5, 6]) === true)
  console.assert(belowZero([1, -1, 2, -2, 5, -5, 4, -4]) === false)
  console.assert(belowZero([1, -1, 2, -2, 5, -5, 4, -5]) === true)
  console.assert(belowZero([1, -2, 2, -2, 5, -5, 4, -4]) === true)
}

testBelowZero()

const testBelowZero = () => {
  console.assert(belowZero([1, 2, 3]) === false)
  console.assert(belowZero([1, 2, -4, 5]) === true)
}
testBelowZero()


Prompt:
/* For a given list of input numbers, calculate Mean Absolute Deviation
  around the mean of this dataset.
  Mean Absolute Deviation is the average absolute difference between each
  element and a centerpoint (mean in this case):
  MAD = average | x - x_mean |
  >>> meanAbsoluteDeviation([1.0, 2.0, 3.0, 4.0])
  1.0
  */
const meanAbsoluteDeviation = (numbers) => {

  var mean = numbers.reduce((prev, item) => {
    return prev + item;
  }, 0) / numbers.length;
  return numbers.reduce((prev, item) => {
    return prev + Math.abs(item - mean);
  }, 0) / numbers.length;

}

const testMeanAbsoluteDeviation = () => {
  console.assert(
    Math.abs(meanAbsoluteDeviation([1.0, 2.0, 3.0]) - 2.0 / 3.0) < 1e-6
  )
  console.assert(
    Math.abs(meanAbsoluteDeviation([1.0, 2.0, 3.0, 4.0]) - 1.0) < 1e-6
  )
  console.assert(
    Math.abs(meanAbsoluteDeviation([1.0, 2.0, 3.0, 4.0, 5.0]) - 6.0 / 5.0) < 1e-6
  )
}

testMeanAbsoluteDeviation()

const testMeanAbsoluteDeviation = () => {
  console.assert(
    Math.abs(meanAbsoluteDeviation([1.0, 2.0, 3.0, 4.0]) - 1.0) < 1e-6
  )
}
testMeanAbsoluteDeviation()


Prompt:
/* Insert a number 'delimeter' between every two consecutive elements of input list `numbers'
  >>> intersperse([], 4)
  []
  >>> intersperse([1, 2, 3], 4)
  [1, 4, 2, 4, 3]
  */
const intersperse = (numbers, delimeter) => {

  if (!Array.isArray(numbers) || numbers.length == 0)
    return [];
  var result = [];
  for (const n of numbers) {
    result.push(n, delimeter);
  }
  result.pop();
  return result;
}

const testIntersperse = () => {
  console.assert(JSON.stringify(intersperse([], 7)) === JSON.stringify([]))
  console.assert(
    JSON.stringify(
      intersperse([5, 6, 3, 2], 8)) === JSON.stringify([5, 8, 6, 8, 3, 8, 2])
  )
  console.assert(
    JSON.stringify(
      intersperse([2, 2, 2], 2)) === JSON.stringify([2, 2, 2, 2, 2])
  )
}

testIntersperse()

const testIntersperse = () => {
  console.assert(JSON.stringify(intersperse([], 4)) === JSON.stringify([]))
  console.assert(
    JSON.stringify(
      intersperse([1,2,3], 4)) === JSON.stringify([1,4,2,4,3])
  )
}
testIntersperse()


Prompt:
/* Input to this function is a string represented multiple groups for nested parentheses separated by spaces.
  For each of the group, output the deepest level of nesting of parentheses.
  E.g. (()()) has maximum two levels of nesting while ((())) has three.

  >>> parseNestedParens('(()()) ((())) () ((())()())')
  [2, 3, 1, 3]
  */
const parseNestedParens = (paren_string) => {

  var parseParenGroup = function (s) {
    let depth = 0, max_depth = 0;
    for (const c of s) {
      if (c == '(') {
        depth += 1;
        max_depth = Math.max(max_depth, depth);
      } else {
        depth -= 1;
      }
    }
    return max_depth;
  }
  return paren_string.split(' ')
          .filter(x => x != '')
          .map(x => parseParenGroup(x));
}

const testParseNestedParens = () => {
  console.assert(
    JSON.stringify(parseNestedParens('(()()) ((())) () ((())()())')) ===
      JSON.stringify([2, 3, 1, 3])
  )
  console.assert(
    JSON.stringify(parseNestedParens('() (()) ((())) (((())))')) ===
      JSON.stringify([1, 2, 3, 4])
  )
  console.assert(
    JSON.stringify(parseNestedParens('(()(())((())))')) === JSON.stringify([4])
  )
}

testParseNestedParens()

const testParseNestedParens = () => {
  console.assert(
    JSON.stringify(parseNestedParens('(()()) ((())) () ((())()())')) ===
      JSON.stringify([2, 3, 1, 3])
  )
}
testParseNestedParens()


Prompt:
/* Filter an input list of strings only for ones that contain given substring
  >>> filterBySubstring([], 'a')
  []
  >>> filterBySubstring(['abc', 'bacd', 'cde', 'array'], 'a')
  ['abc', 'bacd', 'array']
  */
const filterBySubstring = (strings, substring) => {

  return strings.filter(x => x.indexOf(substring) != -1);
}

const testFilterBySubstring = () => {
  console.assert(
    JSON.stringify(filterBySubstring([], 'john')) === JSON.stringify([])
  )
  console.assert(
    JSON.stringify(
      filterBySubstring(
        ['xxx', 'asd', 'xxy', 'john doe', 'xxxAAA', 'xxx'],
        'xxx'
      )
    ) === JSON.stringify(['xxx', 'xxxAAA', 'xxx'])
  )
  console.assert(
    JSON.stringify(
      filterBySubstring(
        ['xxx', 'asd', 'aaaxxy', 'john doe', 'xxxAAA', 'xxx'],
        'xx'
      )
    ) === JSON.stringify(['xxx', 'aaaxxy', 'xxxAAA', 'xxx'])
  )
  console.assert(
    JSON.stringify(
      filterBySubstring(['grunt', 'trumpet', 'prune', 'gruesome'], 'run')
    ) === JSON.stringify(['grunt', 'prune'])
  )
}

testFilterBySubstring()

const testFilterBySubstring = () => {
  console.assert(
    JSON.stringify(filterBySubstring([], 'a')) === JSON.stringify([])
  )
  console.assert(
    JSON.stringify(
      filterBySubstring(
        ['abc', 'bacd', 'cde', 'array'], 'a'
      )
    ) === JSON.stringify(['abc', 'bacd', 'array'])
  )
}
testFilterBySubstring()


Prompt:
/* For a given list of integers, return a tuple consisting of a sum and a product of all the integers in a list.
  Empty sum should be equal to 0 and empty product should be equal to 1.
  >>> sumProduct([])
  (0, 1)
  >>> sumProduct([1, 2, 3, 4])
  (10, 24)
  */
const sumProduct = (numbers, int) => {

  var sum_value = 0, prod_value = 1;
  for (const n of numbers) {
    sum_value += n;
    prod_value *= n;
  }
  return [sum_value, prod_value];
}

const testSumProduct = () => {
  console.assert(JSON.stringify(sumProduct([])) === JSON.stringify([0, 1]))
  console.assert(
    JSON.stringify(sumProduct([1, 1, 1])) === JSON.stringify([3, 1])
  )
  console.assert(
    JSON.stringify(sumProduct([100, 0])) === JSON.stringify([100, 0])
  )
  console.assert(
    JSON.stringify(
      sumProduct([3, 5, 7])) === JSON.stringify([3 + 5 + 7, 3 * 5 * 7])
  )
  console.assert(JSON.stringify(sumProduct([10])) === JSON.stringify([10, 10]))
}

testSumProduct()

const testSumProduct = () => {
  console.assert(JSON.stringify(sumProduct([])) === JSON.stringify([0, 1]))
  console.assert(
    JSON.stringify(sumProduct([1, 2,3,4])) === JSON.stringify([10, 24])
  )
}
testSumProduct()


Prompt:
/* From a given list of integers, generate a list of rolling maximum element found until given moment
  in the sequence.
  >>> rollingMax([1, 2, 3, 2, 3, 4, 2])
  [1, 2, 3, 3, 3, 4, 4]
  */
const rollingMax = (numbers) => {

  var running_max, result = [];
  for (const n of numbers) {
    if (running_max == undefined)
      running_max = n;
    else
      running_max = Math.max(running_max, n);
    result.push(running_max);
  }
  return result;
}

const testRollingMax = () => {
  console.assert(JSON.stringify(rollingMax([])) === JSON.stringify([]))
  console.assert(
    JSON.stringify(rollingMax([1, 2, 3, 4])) === JSON.stringify([1, 2, 3, 4])
  )
  console.assert(
    JSON.stringify(rollingMax([4, 3, 2, 1])) === JSON.stringify([4, 4, 4, 4])
  )
  console.assert(
    JSON.stringify(
      rollingMax([3, 2, 3, 100, 3])) === JSON.stringify([3, 3, 3, 100, 100])
  )
}

testRollingMax()

const testRollingMax = () => {
  console.assert(JSON.stringify(rollingMax([1, 2, 3, 2, 3, 4, 2])) === JSON.stringify([1, 2, 3, 3, 3, 4, 4]))
}
testRollingMax()


Prompt:
/* Test if gniven strig is a palindrome */
const isPalindrome = (string) => {
  return string == string.split('').reverse().join('');
}

/* Find the shortest palindrome that begins with a supplied string.
  Algorithm idea is simple:
  - Find the longest postfix of supplied string that is a palindrome.
  - Append to the end of the string reverse of a string prefix that comes before the palindromic suffix.
  >>> makePalindrome('')
  ''
  >>> makePalindrome('cat')
  'catac'
  >>> makePalindrome('cata')
  'catac'
  */
const makePalindrome = (string) => {

  if (string == '')
    return '';
  var beginning_of_suffix = 0;
  while (!isPalindrome(string.slice(beginning_of_suffix)))
    beginning_of_suffix += 1;
  return string + string.slice(0, beginning_of_suffix).split('').reverse().join('');
}

const testmakePalindrome = () => {
  console.assert(makePalindrome('') === '')
  console.assert(makePalindrome('x') === 'x')
  console.assert(makePalindrome('xyz') === 'xyzyx')
  console.assert(makePalindrome('xyx') === 'xyx')
  console.assert(makePalindrome('jerry') === 'jerryrrej')
}

testmakePalindrome()

const isPalindrome = (string) => {
  return string == string.split('').reverse().join('');
}

const makePalindrome = (string) => {

const testmakePalindrome = () => {
  console.assert(makePalindrome('') === '')
  console.assert(makePalindrome('cat') === 'catac')
  console.assert(makePalindrome('cata') === 'catac')
}
testmakePalindrome()


Prompt:
/* Input are two strings a and b consisting only of 1s and 0s.
  Perform binary XOR on these inputs and return result also as a string.
  >>> stringXor('010', '110')
  '100'
  */
const stringXor = (a, b) => {

  var xor = function (i, j) {
    if (i == j)
      return '0';
    else
      return '1';
  }
  return a.split('').map((item, index) => xor(item, b[index])).join('');
}

const testStringXor = () => {
  console.assert(stringXor('111000', '101010') === '010010')
  console.assert(stringXor('1', '1') === '0')
  console.assert(stringXor('0101', '0000') === '0101')
}

testStringXor()

const testStringXor = () => {
  console.assert(stringXor('010', '110') === '100')
}
testStringXor()


Prompt:
/* Out of list of strings, return the longest one. Return the first one in case of multiple
  strings of the same length. Return null in case the input list is empty.
  >>> longest([])

  >>> longest(['a', 'b', 'c'])
  'a'
  >>> longest(['a', 'bb', 'ccc'])
  'ccc'
  */
const longest = (strings) => {

  if (!Array.isArray(strings) || strings.length == 0)
    return null;
  var maxlen = Math.max(...strings.map(x => x.length));
  for (const s of strings) {
    if (s.length == maxlen) {
      return s;
    }
  }
}

const testLongest = () => {
  console.assert(longest([]) === null)
  console.assert(longest(['x', 'y', 'z']) === 'x')
  console.assert(longest(['x', 'yyy', 'zzzz', 'www', 'kkkk', 'abc']) === 'zzzz')
}

testLongest()

const testLongest = () => {
  console.assert(longest([]) === null)
  console.assert(longest(['a', 'b', 'c']) === 'a')
  console.assert(longest(['a', 'bb', 'ccc']) === 'ccc')
}
testLongest()


Prompt:
/* Return a greatest common divisor of two integers a and b
  >>> greatestCommonDivisor(3, 5)
  1
  >>> greatestCommonDivisor(25, 15)
  5
  */
const greatestCommonDivisor = (a, b) => {

  while (b != 0) {
    let temp = a;
    a = b;
    b = temp % b;
  }
  return a;
}

const testGreatestCommonDivisor = () => {
  console.assert(greatestCommonDivisor(3, 7) === 1)
  console.assert(greatestCommonDivisor(10, 15) === 5)
  console.assert(greatestCommonDivisor(49, 14) === 7)
  console.assert(greatestCommonDivisor(144, 60) === 12)
}

testGreatestCommonDivisor()

const testGreatestCommonDivisor = () => {
  console.assert(greatestCommonDivisor(3, 5) === 1)
  console.assert(greatestCommonDivisor(25, 15) === 5)
}
testGreatestCommonDivisor()


Prompt:
/* Return list of all prefixes from shortest to longest of the input string
  >>> allPrefixes('abc')
  ['a', 'ab', 'abc']
  */
const allPrefixes = (string) => {

  var result = [];
  for (let i = 0; i < string.length; i++) {
    result.push(string.slice(0, i+1));
  }
  return result;
}

const testAllPrefixes = () => {
  console.assert(JSON.stringify(allPrefixes('')) === JSON.stringify([]))
  console.assert(
    JSON.stringify(
      allPrefixes('asdfgh')) ===
        JSON.stringify(['a', 'as', 'asd', 'asdf', 'asdfg', 'asdfgh'])
  )
  console.assert(
    JSON.stringify(allPrefixes('WWW')) === JSON.stringify(['W', 'WW', 'WWW'])
  )
}

testAllPrefixes()

const testAllPrefixes = () => {
  console.assert(
    JSON.stringify(
      allPrefixes('abc')) ===
        JSON.stringify(['a', 'ab', 'abc'])
  )
}
testAllPrefixes()


Prompt:
/* Return a string containing space-delimited numbers starting from 0 upto n inclusive.
  >>> stringSequence(0)
  '0'
  >>> stringSequence(5)
  '0 1 2 3 4 5'
  */
const stringSequence = (n) => {

  return [...Array(n).keys(), n].join(' ')
}

const testStringSequence = () => {
  console.assert(stringSequence(0) === '0')
  console.assert(stringSequence(3) === '0 1 2 3')
  console.assert(stringSequence(10) === '0 1 2 3 4 5 6 7 8 9 10')
}

testStringSequence()

const testStringSequence = () => {
  console.assert(stringSequence(0) === '0')
  console.assert(stringSequence(5) === '0 1 2 3 4 5')
}
testStringSequence()


Prompt:
/* Given a string, find out how many distinct characters (regardless of case) does it consist of
  >>> countDistinctCharacters('xyzXYZ')
  3
  >>> countDistinctCharacters('Jerry')
  4
  */
const countDistinctCharacters = (string) => {

  return (new Set(string.toLowerCase())).size;

}

const testCountDistinctCharacters = () => {
  console.assert(countDistinctCharacters('') === 0)
  console.assert(countDistinctCharacters('abcde') === 5)
  console.assert(countDistinctCharacters('abcde' + 'cade' + 'CADE') === 5)
  console.assert(countDistinctCharacters('aaaaAAAAaaaa') === 1)
  console.assert(countDistinctCharacters('Jerry jERRY JeRRRY') === 5)
}

testCountDistinctCharacters()

const testCountDistinctCharacters = () => {
  console.assert(countDistinctCharacters('xyzXYZ') === 3)
  console.assert(countDistinctCharacters('Jerry') === 4)
}
testCountDistinctCharacters()


Prompt:
/* Input to this function is a string representing musical notes in a special ASCII format.
  Your task is to parse this string and return list of integers corresponding to how many beats does each
  not last.

  Here is a legend:
  'o' - whole note, lasts four beats
  'o|' - half note, lasts two beats
  '.|' - quater note, lasts one beat

  >>> parseMusic('o o| .| o| o| .| .| .| .| o o')
  [4, 2, 1, 2, 2, 1, 1, 1, 1, 4, 4]
  */
const parseMusic = (music_string) => {

  const note_map = {'o': 4, 'o|': 2, '.|': 1};
  return music_string.split(' ').filter(x => x != '').map(x => note_map[x]);
}

const testParseMusic = () => {
  console.assert(JSON.stringify(parseMusic('')) === JSON.stringify([]))
  console.assert(
    JSON.stringify(parseMusic('o o o o')) === JSON.stringify([4, 4, 4, 4])
  )
  console.assert(
    JSON.stringify(parseMusic('.| .| .| .|')) === JSON.stringify([1, 1, 1, 1])
  )
  console.assert(
    JSON.stringify(parseMusic('o| o| .| .| o o o o')) ===
      JSON.stringify([2, 2, 1, 1, 4, 4, 4, 4])
  )
  console.assert(
    JSON.stringify(parseMusic('o| .| o| .| o o| o o|')) ===
      JSON.stringify([2, 1, 2, 1, 4, 2, 4, 2])
  )
}

testParseMusic()

const testParseMusic = () => {
  console.assert(JSON.stringify(parseMusic('o o| .| o| o| .| .| .| .| o o')) === JSON.stringify([4, 2, 1, 2, 2, 1, 1, 1, 1, 4, 4]))
}
testParseMusic()


Prompt:
/* Find how many times a given substring can be found in the original string. Count overlaping cases.
  >>> howManyTimes('', 'a')
  0
  >>> howManyTimes('aaa', 'a')
  3
  >>> howManyTimes('aaaa', 'aa')
  3
  */
const howManyTimes = (string, substring) => {

  var times = 0;
  for (let i = 0; i < string.length - substring.length + 1; i++) {
    if (string.slice(i, i+substring.length) == substring) {
      times += 1;
    }
  }
  return times;
}

const testHowManyTimes = () => {
  console.assert(howManyTimes('', 'x') === 0)
  console.assert(howManyTimes('xyxyxyx', 'x') === 4)
  console.assert(howManyTimes('cacacacac', 'cac') === 4)
  console.assert(howManyTimes('john doe', 'john') === 1)
}

testHowManyTimes()

const testHowManyTimes = () => {
  console.assert(howManyTimes('', 'a') === 0)
  console.assert(howManyTimes('aaa', 'a') === 3)
  console.assert(howManyTimes('aaaa', 'aa') === 3)
}
testHowManyTimes()


Prompt:
/* Input is a space-delimited string of numberals from 'zero' to 'nine'.
  Valid choices are 'zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight' and 'nine'.
  Return the string with numbers sorted from smallest to largest
  >>> sortNumbers('three one five')
  'one three five'
  */
const sortNumbers = (numbers) => {

  const value_map = {
    'zero': 0,
    'one': 1,
    'two': 2,
    'three': 3,
    'four': 4,
    'five': 5,
    'six': 6,
    'seven': 7,
    'eight': 8,
    'nine': 9
  };
  return numbers.split(' ')
          .filter(x => x != '')
          .sort((a, b) => value_map[a] - value_map[b])
          .join(' ');
}

const testSortNumbers = () => {
  console.assert(sortNumbers('') === '')
  console.assert(sortNumbers('three') === 'three')
  console.assert(sortNumbers('three five nine') === 'three five nine')
  console.assert(
    sortNumbers(
      'five zero four seven nine eight') === 'zero four five seven eight nine'
  )
  console.assert(
    sortNumbers(
      'six five four three two one zero') === 'zero one two three four five six'
  )
}

testSortNumbers()

const testSortNumbers = () => {
  console.assert(sortNumbers('three one five') === 'one three five')
}
testSortNumbers()


Prompt:
/* From a supplied list of numbers (of length at least two) select and return two that are the closest to each
  other and return them in order (smaller number, larger number).
  >>> findClosestElements([1.0, 2.0, 3.0, 4.0, 5.0, 2.2])
  (2.0, 2.2)
  >>> findClosestElements([1.0, 2.0, 3.0, 4.0, 5.0, 2.0])
  (2.0, 2.0)
  */
const findClosestElements = (numbers) => {

  var closest_pair, distance;
  for (let i = 0; i < numbers.length; i++)
    for (let j = 0; j < numbers.length; j++)
      if (i != j) {
        let a = numbers[i], b = numbers[j];
        if (distance == null) {
          distance = Math.abs(a - b);
          closest_pair = [Math.min(a, b), Math.max(a, b)];
        } else {
          let new_distance = Math.abs(a - b);
          if (new_distance < distance) {
            distance = new_distance;
            closest_pair = [Math.min(a, b), Math.max(a, b)];
          }
        }
      }
  return closest_pair;
}

const testFindClosestElements = () => {
  console.assert(
    JSON.stringify(findClosestElements([1.0, 2.0, 3.9, 4.0, 5.0, 2.2])) ===
      JSON.stringify([3.9, 4.0])
  )
  console.assert(
    JSON.stringify(findClosestElements([1.0, 2.0, 5.9, 4.0, 5.0])) ===
      JSON.stringify([5.0, 5.9])
  )
  console.assert(
    JSON.stringify(findClosestElements([1.0, 2.0, 3.0, 4.0, 5.0, 2.2])) ===
      JSON.stringify([2.0, 2.2])
  )
  console.assert(
    JSON.stringify(findClosestElements([1.0, 2.0, 3.0, 4.0, 5.0, 2.0])) ===
      JSON.stringify([2.0, 2.0])
  )
  console.assert(
    JSON.stringify(findClosestElements([1.1, 2.2, 3.1, 4.1, 5.1])) ===
      JSON.stringify([2.2, 3.1])
  )
}

testFindClosestElements()

const testFindClosestElements = () => {
  console.assert(
    JSON.stringify(findClosestElements([1.0, 2.0, 3.0, 4.0, 5.0, 2.2])) ===
      JSON.stringify([2.0, 2.2])
  )
  console.assert(
    JSON.stringify(findClosestElements([1.0, 2.0, 3.0, 4.0, 5.0, 2.0])) ===
      JSON.stringify([2.0, 2.0])
  )
}
testFindClosestElements()


Prompt:
/* Given list of numbers (of at least two elements), apply a linear transform to that list,
  such that the smallest number will become 0 and the largest will become 1
  >>> rescaleToUnit([1.0, 2.0, 3.0, 4.0, 5.0])
  [0.0, 0.25, 0.5, 0.75, 1.0]
  */
const rescaleToUnit = (numbers) => {

  var min_number = Math.min(...numbers);
  var max_number = Math.max(...numbers);
  return numbers.map(x => (x - min_number) / (max_number - min_number));
}

const testRescaleToUnit = () => {
  console.assert(
    JSON.stringify(rescaleToUnit([2.0, 49.9])) === JSON.stringify([0.0, 1.0])
  )
  console.assert(
    JSON.stringify(rescaleToUnit([100.0, 49.9])) === JSON.stringify([1.0, 0.0])
  )
  console.assert(
    JSON.stringify(rescaleToUnit([1.0, 2.0, 3.0, 4.0, 5.0])) ===
      JSON.stringify([0.0, 0.25, 0.5, 0.75, 1.0])
  )
  console.assert(
    JSON.stringify(rescaleToUnit([2.0, 1.0, 5.0, 3.0, 4.0])) ===
      JSON.stringify([0.25, 0.0, 1.0, 0.5, 0.75])
  )
  console.assert(
    JSON.stringify(rescaleToUnit([12.0, 11.0, 15.0, 13.0, 14.0])) ===
      JSON.stringify([0.25, 0.0, 1.0, 0.5, 0.75])
  )
}

testRescaleToUnit()

const testRescaleToUnit = () => {
  console.assert(
    JSON.stringify(rescaleToUnit([1.0, 2.0, 3.0, 4.0, 5.0])) ===
      JSON.stringify([0.0, 0.25, 0.5, 0.75, 1.0])
  )
}
testRescaleToUnit()


Prompt:
/* Filter given list of any python values only for integers
  >>> filterIntegers(['a', 3.14, 5])
  [5]
  >>> filterIntegers([1, 2, 3, 'abc', {}, []])
  [1, 2, 3]
  */
const filterIntegers = (values) => {

  return values.filter(x => Number.isInteger(x));
}

const testFilterIntegers = () => {
  console.assert(JSON.stringify(filterIntegers([])) === JSON.stringify([]))
  console.assert(
    JSON.stringify(filterIntegers([4, {}, [], 23.2, 9, 'adasd'])) ===
      JSON.stringify([4, 9])
  )
  console.assert(
    JSON.stringify(filterIntegers([3, 'c', 3, 3, 'a', 'b'])) ===
      JSON.stringify([3, 3, 3])
  )
}

testFilterIntegers()

const testFilterIntegers = () => {
  console.assert(JSON.stringify(filterIntegers(['a', 3.14, 5])) === JSON.stringify([5]))
  console.assert(
    JSON.stringify(filterIntegers([1, 2, 3, 'abc', {}, []])) ===
      JSON.stringify([1,2,3])
  )
}
testFilterIntegers()


Prompt:
/* Return length of given string
  >>> strlen('')
  0
  >>> strlen('abc')
  3
  */
const strlen = (string) => {

const testStrlen = () => {
  console.assert(strlen('') === 0)
  console.assert(strlen('x') === 1)
  console.assert(strlen('asdasnakj') === 9)
}

testStrlen()

const testStrlen = () => {
  console.assert(strlen('') === 0)
  console.assert(strlen('abc') === 3)
}
testStrlen()


Prompt:
/* For a given number n, find the largest number that divides n evenly, smaller than n
  >>> largestDivisor(15)
  5
  */
const largestDivisor = (n) => {

  for (let i = n - 1; i >= 0; i--)
    if (n % i == 0)
      return i;
}

const testLargestDivisor = () => {
  console.assert(largestDivisor(3) === 1)
  console.assert(largestDivisor(7) === 1)
  console.assert(largestDivisor(10) === 5)
  console.assert(largestDivisor(100) === 50)
  console.assert(largestDivisor(49) === 7)
}

testLargestDivisor()

const testLargestDivisor = () => {
  console.assert(largestDivisor(15) === 5)
}
testLargestDivisor()


Prompt:
/* Return list of prime factors of given integer in the order from smallest to largest.
  Each of the factors should be listed number of times corresponding to how many times it appeares in factorization.
  Input number should be equal to the product of all factors
  >>> factorize(8)
  [2, 2, 2]
  >>> factorize(25)
  [5, 5]
  >>> factorize(70)
  [2, 5, 7]
  */
const factorize = (n) => {

  var fact = [], i = 2;
  while (i <= Math.sqrt(n) + 1) {
    if (n % i == 0) {
      fact.push(i);
      n = n / i;
    } else {
      i += 1;
    }
  }

  if (n > 1)
    fact.push(n);
  return fact;
}

const testFactorize = () => {
  console.assert(JSON.stringify(factorize(2)) === JSON.stringify([2]))
  console.assert(JSON.stringify(factorize(4)) === JSON.stringify([2, 2]))
  console.assert(JSON.stringify(factorize(8)) === JSON.stringify([2, 2, 2]))
  console.assert(JSON.stringify(factorize(3 * 19)) === JSON.stringify([3, 19]))
  console.assert(
    JSON.stringify(factorize(3 * 19 * 3 * 19)) ===
      JSON.stringify([3, 3, 19, 19])
  )
  console.assert(
    JSON.stringify(factorize(3 * 19 * 3 * 19 * 3 * 19)) ===
      JSON.stringify([3, 3, 3, 19, 19, 19])
  )
  console.assert(
    JSON.stringify(factorize(3 * 19 * 19 * 19)) ===
      JSON.stringify([3, 19, 19, 19])
  )
  console.assert(
    JSON.stringify(factorize(3 * 2 * 3)) === JSON.stringify([2, 3, 3])
  )
}

testFactorize()

const testFactorize = () => {
  console.assert(JSON.stringify(factorize(8)) === JSON.stringify([2, 2, 2]))
  console.assert(JSON.stringify(factorize(25)) === JSON.stringify([5,5]))
  console.assert(
    JSON.stringify(factorize(70)) ===
      JSON.stringify([2,5,7])
  )
}
testFactorize()


Prompt:
/* From a list of integers, remove all elements that occur more than once.
  Keep order of elements left the same as in the input.
  >>> removeDuplicates([1, 2, 3, 2, 4])
  [1, 3, 4]
  */
const removeDuplicates = (numbers) => {

  var dict = new Object();
  for (const num of numbers) {
    if (num in dict) {
      dict[num] += 1;
    } else {
      dict[num] = 1;
    }
  }
  return numbers.filter(x => dict[x] <= 1);
}

const testRemoveDuplicates = () => {
  console.assert(JSON.stringify(removeDuplicates([])) === JSON.stringify([]))
  console.assert(
    JSON.stringify(removeDuplicates([1, 2, 3, 4])) ===
      JSON.stringify([1, 2, 3, 4])
  )
  console.assert(
    JSON.stringify(removeDuplicates([1, 2, 3, 2, 4, 3, 5])) ===
      JSON.stringify([1, 4, 5])
  )
}

testRemoveDuplicates()

const testRemoveDuplicates = () => {
  console.assert(
    JSON.stringify(removeDuplicates([1, 2, 3, 2,4])) ===
      JSON.stringify([1,3, 4])
  )
}
testRemoveDuplicates()


Prompt:
/* For a given string, flip lowercase characters to uppercase and uppercase to lowercase.
  >>> flipCase('Hello')
  'hELLO'
  */
const flipCase = (string) => {

  return string.split('')
          .map(x => (x.toUpperCase() == x ? x.toLowerCase() : x.toUpperCase()))
          .join('');
}

const testFlipCase = () => {
  console.assert(flipCase('') === '')
  console.assert(flipCase('Hello!') === 'hELLO!')
  console.assert(
    flipCase(
      'These violent delights have violent ends') ===
        'tHESE VIOLENT DELIGHTS HAVE VIOLENT ENDS'
  )
}

testFlipCase()

const testFlipCase = () => {
  console.assert(flipCase('Hello') === 'hELLO')
}
testFlipCase()


Prompt:
/* Concatenate list of strings into a single string
  >>> concatenate([])
  ''
  >>> concatenate(['a', 'b', 'c'])
  'abc'
  */
const concatenate = (strings) => {

const testConcatenate = () => {
  console.assert(concatenate([]) === '')
  console.assert(concatenate(['x', 'y', 'z']) === 'xyz')
  console.assert(concatenate(['x', 'y', 'z', 'w', 'k']) === 'xyzwk')
}

testConcatenate()

const testConcatenate = () => {
  console.assert(concatenate([]) === '')
  console.assert(concatenate(['a', 'b', 'c']) === 'abc')
}
testConcatenate()


Prompt:
/* Filter an input list of strings only for ones that start with a given prefix.
  >>> filterByPrefix([], 'a')
  []
  >>> filterByPrefix(['abc', 'bcd', 'cde', 'array'], 'a')
  ['abc', 'array']
  */
const filterByPrefix = (strings, prefix) => {

  return strings.filter(x => x.startsWith(prefix));
}

const testFilterByPrefix = () => {
  console.assert(
    JSON.stringify(filterByPrefix([], 'john')) === JSON.stringify([])
  )
  console.assert(
    JSON.stringify(
      filterByPrefix(['xxx', 'asd', 'xxy', 'john doe', 'xxxAAA', 'xxx'], 'xxx')
    ) === JSON.stringify(['xxx', 'xxxAAA', 'xxx'])
  )
}

testFilterByPrefix()

const testFilterByPrefix = () => {
  console.assert(
    JSON.stringify(filterByPrefix([], 'a')) === JSON.stringify([])
  )
  console.assert(
    JSON.stringify(
      filterByPrefix(['abc', 'bcd', 'cde', 'array'], 'a')
    ) === JSON.stringify(['abc', 'array'])
  )
}
testFilterByPrefix()


Prompt:
/*Return only positive numbers in the list.
  >>> getPositive([-1, 2, -4, 5, 6])
  [2, 5, 6]
  >>> getPositive([5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10])
  [5, 3, 2, 3, 9, 123, 1]
  */
const getPositive = (l) => {

const testGetPositive = () => {
  console.assert(
    JSON.stringify(getPositive([-1, -2, 4, 5, 6])) === JSON.stringify([4, 5, 6])
  )
  console.assert(
    JSON.stringify(getPositive([5, 3, -5, 2, 3, 3, 9, 0, 123, 1, -10])) ===
      JSON.stringify([5, 3, 2, 3, 3, 9, 123, 1])
  )
  console.assert(JSON.stringify(getPositive([-1, -2])) === JSON.stringify([]))
  console.assert(JSON.stringify(getPositive([])) === JSON.stringify([]))
}

testGetPositive()

const testGetPositive = () => {
  console.assert(
    JSON.stringify(getPositive([-1, 2, -4, 5, 6])) === JSON.stringify([2, 5, 6])
  )
  console.assert(
    JSON.stringify(getPositive([5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10])) ===
      JSON.stringify([5, 3, 2, 3, 9, 123, 1])
  )
}
testGetPositive()


Prompt:
/*Return true if a given number is prime, and false otherwise.
  >>> isPrime(6)
  false
  >>> isPrime(101)
  true
  >>> isPrime(11)
  true
  >>> isPrime(13441)
  true
  >>> isPrime(61)
  true
  >>> isPrime(4)
  false
  >>> isPrime(1)
  false
  */
const isPrime = (n) => {

  if (n < 2)
    return false;
  for (let k = 2; k < n - 1; k++)
    if (n % k == 0)
      return false;
  return true;
}

const testIsPrime = () => {
  console.assert(isPrime(6) === false)
  console.assert(isPrime(101) === true)
  console.assert(isPrime(11) === true)
  console.assert(isPrime(13441) === true)
  console.assert(isPrime(61) === true)
  console.assert(isPrime(4) === false)
  console.assert(isPrime(1) === false)
  console.assert(isPrime(5) === true)
  console.assert(isPrime(11) === true)
  console.assert(isPrime(17) === true)
  console.assert(isPrime(5 * 17) === false)
  console.assert(isPrime(11 * 7) === false)
  console.assert(isPrime(13441 * 19) === false)
}

testIsPrime()

const testIsPrime = () => {
  console.assert(isPrime(6) === false)
  console.assert(isPrime(101) === true)
  console.assert(isPrime(11) === true)
  console.assert(isPrime(13441) === true)
  console.assert(isPrime(61) === true)
  console.assert(isPrime(4) === false)
  console.assert(isPrime(1) === false)
}
testIsPrime()


Prompt:
/*
  Evaluates polynomial with coefficients xs at point x.
  return xs[0] + xs[1] * x + xs[1] * x^2 + .... xs[n] * x^n
  */
const poly = (xs, x) => {
  return xs.reduce((prev, item, index) => {
    return prev + item * Math.pow(x, index);
  }, 0);
}

/*
  xs are coefficients of a polynomial.
  findZero find x such that poly(x) = 0.
  findZero returns only only zero point, even if there are many.
  Moreover, findZero only takes list xs having even number of coefficients
  and largest non zero coefficient as it guarantees
  a solution.
  >>> round(findZero([1, 2]), 2) # f(x) = 1 + 2x
  -0.5
  >>> round(findZero([-6, 11, -6, 1]), 2) # (x - 1) * (x - 2) * (x - 3) = -6 + 11x - 6x^2 + x^3
  1.0
  */
const findZero = (xs) => {

  var begin = -1.0, end = 1.0;
  while (poly(xs, begin) * poly(xs, end) > 0) {
    begin *= 2.0;
    end *= 2.0;
  }
  while (end - begin > 1e-10) {
    let center = (begin + end) / 2.0;
    if (poly(xs, center) * poly(xs, begin) > 0)
      begin = center;
    else
      end = center;
  }
  return begin;
}

const testfindZero = () => {
  const getRandomIntInclusive = (min = 0, max = 9) => {
    min = Math.ceil(min)
    max = Math.floor(max)
    return Math.floor(Math.random() * (max - min + 1)) + min
  }

  for (let i = 0; i < 100; i++) {
    let ncoeff = 2 * getRandomIntInclusive(1, 4);
    let coeffs = [];
    for (let j = 0; j < ncoeff; j++) {
      let coeff = getRandomIntInclusive(-10, 10);
      if (coeff === 0)
        coeff = 1;
      coeffs.push(coeff);
    }
    let solution = findZero(coeffs);
    console.assert(Math.abs(poly(coeffs, solution)) < 1e-4);
  }
}
testfindZero()

const poly = (xs, x) => {
  return xs.reduce((prev, item, index) => {
    return prev + item * Math.pow(x, index);
  }, 0);
}

const findZero = (xs) => {

const testPoly = () => {
  console.assert(Math.abs(findZero([1,2])+0.5 < 1e-4));
  console.assert(Math.abs(findZero([-6,11,-6,1])-1 < 1e-4));
}
testPoly()
testfindZero()


Prompt:
/*This function takes a list l and returns a list l' such that
  l' is identical to l in the indicies that are not divisible by three, while its values at the indicies that are divisible by three are equal
  to the values of the corresponding indicies of l, but sorted.
  >>> sortThird([1, 2, 3])
  [1, 2, 3]
  >>> sortThird([5, 6, 3, 4, 8, 9, 2])
  [2, 6, 3, 4, 8, 9, 5]
  */
const sortThird = (l) => {

  var three = l.filter((item, index) => index % 3 == 0);
  three.sort((a, b) => (a - b));
  return l.map((item, index) => (index % 3 == 0 ? three[index / 3] : item));
}

const testSortThird = () => {
  console.assert(
    JSON.stringify(sortThird([1, 2, 3])) == JSON.stringify([1, 2, 3])
  )
  console.assert(
    JSON.stringify(sortThird([5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10])) ==
      JSON.stringify([1, 3, -5, 2, -3, 3, 5, 0, 123, 9, -10])
  )
  console.assert(
    JSON.stringify(sortThird([5, 8, -12, 4, 23, 2, 3, 11, 12, -10])) ==
      JSON.stringify([-10, 8, -12, 3, 23, 2, 4, 11, 12, 5])
  )
  console.assert(
    JSON.stringify(sortThird([5, 6, 3, 4, 8, 9, 2])) ==
      JSON.stringify([2, 6, 3, 4, 8, 9, 5])
  )
  console.assert(
    JSON.stringify(sortThird([5, 8, 3, 4, 6, 9, 2])) ==
      JSON.stringify([2, 8, 3, 4, 6, 9, 5])
  )
  console.assert(
    JSON.stringify(sortThird([5, 6, 9, 4, 8, 3, 2])) ==
      JSON.stringify([2, 6, 9, 4, 8, 3, 5])
  )
  console.assert(
    JSON.stringify(sortThird([5, 6, 3, 4, 8, 9, 2, 1])) ==
      JSON.stringify([2, 6, 3, 4, 8, 9, 5, 1])
  )
}

testSortThird()

const testSortThird = () => {
  console.assert(
    JSON.stringify(sortThird([1, 2, 3])) == JSON.stringify([1, 2, 3])
  )
  console.assert(
    JSON.stringify(sortThird([5, 6, 3, 4, 8, 9, 2])) ==
      JSON.stringify([2, 6, 3, 4, 8, 9, 5])
  )
}
testSortThird()


Prompt:
/*Return sorted unique elements in a list
  >>> unique([5, 3, 5, 2, 3, 3, 9, 0, 123])
  [0, 2, 3, 5, 9, 123]
  */
const unique = (l) => {

  return Array.from(new Set(l)).sort((a, b) => (a - b));
}

const testUnique = () => {
  console.assert(
    JSON.stringify(unique([5, 3, 5, 2, 3, 3, 9, 0, 123])) ===
      JSON.stringify([0, 2, 3, 5, 9, 123])
  )
}

testUnique()


Prompt:
/*Return maximum element in the list.
  >>> maxElement([1, 2, 3])
  3
  >>> maxElement([5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10])
  123
  */
const maxElement = (l) => {

const testMaxElement = () => {
  console.assert(maxElement([1, 2, 3]) === 3)
  console.assert(maxElement([5, 3, -5, 2, -3, 3, 9, 0, 124, 1, -10]) === 124)
}

testMaxElement()

const testMaxElement = () => {
  console.assert(maxElement([1, 2, 3]) === 3)
  console.assert(maxElement([5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10]) === 123)
}
testMaxElement()


Prompt:
/*Return the number of times the digit 7 appears in integers less than n which are divisible by 11 or 13.
  >>> fizzBuzz(50)
  0
  >>> fizzBuzz(78)
  2
  >>> fizzBuzz(79)
  3
  */
const fizzBuzz = (n) => {

  var ns = [], ans = 0;
  for (let i = 0; i < n; i++)
    if (i % 11 == 0 || i % 13 == 0)
      ns.push(i);
  var s = ns.map(x => x.toString()).join('');
  for (const c of s)
    ans += (c == '7');
  return ans;
}

const testFizzBuzz = () => {
  console.assert(fizzBuzz(50) === 0)
  console.assert(fizzBuzz(78) === 2)
  console.assert(fizzBuzz(79) === 3)
  console.assert(fizzBuzz(100) === 3)
  console.assert(fizzBuzz(200) === 6)
  console.assert(fizzBuzz(4000) === 192)
  console.assert(fizzBuzz(10000) === 639)
  console.assert(fizzBuzz(100000) === 8026)
}

testFizzBuzz()

const testFizzBuzz = () => {
  console.assert(fizzBuzz(50) === 0)
  console.assert(fizzBuzz(78) === 2)
  console.assert(fizzBuzz(79) === 3)
}
testFizzBuzz()


Prompt:
/*This function takes a list l and returns a list l' such that
  l' is identical to l in the odd indicies, while its values at the even indicies are equal
  to the values of the even indicies of l, but sorted.
  >>> sortEven([1, 2, 3])
  [1, 2, 3]
  >>> sortEven([5, 6, 3, 4])
  [3, 6, 5, 4]
  */
const sortEven = (l) => {

  var even = l.filter((item, index) => index % 2 == 0);
  even.sort((a, b) => (a - b));
  return l.map((item, index) => (index % 2 == 0 ? even[index / 2] : item));
}

const testSortEven = () => {
  console.assert(JSON.stringify(sortEven([1, 2, 3])) ===
    JSON.stringify([1, 2, 3]))
  console.assert(JSON.stringify(
    sortEven([5,6,3,4])) ===
    JSON.stringify([3,6,5,4]))
}
testSortEven()


Prompt:
/*
  returns encoded string by cycling groups of three characters.
  */
const encodeCyclic = (s) => {
  var groups = [], groups2 = [];
  for (let i = 0; i < Math.floor((s.length + 2) / 3); i++) {
    groups.push(s.slice(3 * i, Math.min((3 * i + 3), s.length)));
  }
  for (const group of groups) {
    if (group.length == 3)
      groups2.push(group.slice(1) + group[0]);
    else
      groups2.push(group);
  }
  return groups2.join('');
}

/*
  takes as input string encoded with encode_cyclic function. Returns decoded string.
  */
const decodeCyclic = (s) => {

  return encodeCyclic(encodeCyclic(s));
}

const testDecodeCyclic = () => {
  const letters = new Array(26)
    .fill(null)
    .map((v, i) => String.fromCharCode(97 + i));

  for (let i = 0; i < 100; i++) {
    let str = new Array(Math.floor(Math.random() * 20)).fill(null);
    str = str.map(item => letters[Math.floor(Math.random() * letters.length)]).join('');
    let encoded_str = encodeCyclic(str);
    console.assert(decodeCyclic(encoded_str) === str);
  }
}

testDecodeCyclic()

const encodeCyclic = (s) => {
  var groups = [], groups2 = [];
  for (let i = 0; i < Math.floor((s.length + 2) / 3); i++) {
    groups.push(s.slice(3 * i, Math.min((3 * i + 3), s.length)));
  }
  for (const group of groups) {
    if (group.length == 3)
      groups2.push(group.slice(1) + group[0]);
    else
      groups2.push(group);
  }
  return groups2.join('');
}

const decodeCyclic = (s) => {


Prompt:
/*
  primeFib returns n-th number that is a Fibonacci number and it's also prime.
  >>> primeFib(1)
  2
  >>> primeFib(2)
  3
  >>> primeFib(3)
  5
  >>> primeFib(4)
  13
  >>> primeFib(5)
  89
  */
const primeFib = (n) => {

  var isPrime = function (p) {
    if (p < 2)
      return false;
    for (let k = 2; k < Math.min(Math.floor(Math.sqrt(p)) + 1, p - 1); k++) {
      if (p % k == 0)
        return false;
    }
    return true;
  }

  var f = [0, 1];
  while (true) {
    f.push(f.at(-1) + f.at(-2));
    if (isPrime(f.at(-1)))
      n -= 1;
    if (n == 0)
      return f.at(-1);
  }
}

const testPrimeFib = () => {
  console.assert(primeFib(1) === 2)
  console.assert(primeFib(2) === 3)
  console.assert(primeFib(3) === 5)
  console.assert(primeFib(4) === 13)
  console.assert(primeFib(5) === 89)
  console.assert(primeFib(6) === 233)
  console.assert(primeFib(7) === 1597)
  console.assert(primeFib(8) === 28657)
  console.assert(primeFib(9) === 514229)
  console.assert(primeFib(10) === 433494437)
}

testPrimeFib()

const testPrimeFib = () => {
  console.assert(primeFib(1) === 2)
  console.assert(primeFib(2) === 3)
  console.assert(primeFib(3) === 5)
  console.assert(primeFib(4) === 13)
  console.assert(primeFib(5) === 89)
}
testPrimeFib()


Prompt:
/*
  triplesSumToZero takes a list of integers as an input.
  it returns true if there are three distinct elements in the list that
  sum to zero, and false otherwise.

  >>> triplesSumToZero([1, 3, 5, 0])
  false
  >>> triplesSumToZero([1, 3, -2, 1])
  true
  >>> triplesSumToZero([1, 2, 3, 7])
  false
  >>> triplesSumToZero([2, 4, -5, 3, 9, 7])
  true
  >>> triplesSumToZero([1])
  false
  */
const triplesSumToZero = (l) => {

  for (let i = 0; i < l.length; i++)
    for (let j = i + 1; j < l.length; j++)
      for (let k = j + 1; k < l.length; k++)
        if (l[i] + l[j] + l[k] == 0)
          return true;
  return false;
}

const testTriplesSumToZero = () => {
  console.assert(triplesSumToZero([1, 3, 5, 0]) === false)
  console.assert(triplesSumToZero([1, 3, 5, -1]) === false)
  console.assert(triplesSumToZero([1, 3, -2, 1]) === true)
  console.assert(triplesSumToZero([1, 2, 3, 7]) === false)
  console.assert(triplesSumToZero([1, 2, 5, 7]) === false)
  console.assert(triplesSumToZero([2, 4, -5, 3, 9, 7]) === true)
  console.assert(triplesSumToZero([1]) === false)
  console.assert(triplesSumToZero([1, 3, 5, -100]) === false)
  console.assert(triplesSumToZero([100, 3, 5, -100]) === false)
}

testTriplesSumToZero()

const testTriplesSumToZero = () => {
  console.assert(triplesSumToZero([1, 3, 5, 0]) === false)
  console.assert(triplesSumToZero([1, 3, -2, 1]) === true)
  console.assert(triplesSumToZero([1, 2, 3, 7]) === false)
  console.assert(triplesSumToZero([2, 4, -5, 3, 9, 7]) === true)
}
testTriplesSumToZero()


Prompt:
/*
  Imagine a road that's a perfectly straight infinitely long line.
  n cars are driving left to right;  simultaneously, a different set of n cars
  are driving right to left.   The two sets of cars start out being very far from
  each other.  All cars move in the same speed.  Two cars are said to collide
  when a car that's moving left to right hits a car that's moving right to left.
  However, the cars are infinitely sturdy and strong; as a result, they continue moving
  in their trajectory as if they did not collide.

  This function outputs the number of such collisions.
  */
const carRaceCollision = (n) => {

const testCarRaceCollision = () => {
  console.assert(carRaceCollision(2) === 4)
  console.assert(carRaceCollision(3) === 9)
  console.assert(carRaceCollision(4) === 16)
  console.assert(carRaceCollision(8) === 64)
  console.assert(carRaceCollision(10) === 100)
}

testCarRaceCollision()


Prompt:
/*Return list with elements incremented by 1.
  >>> incrList([1, 2, 3])
  [2, 3, 4]
  >>> incrList([5, 3, 5, 2, 3, 3, 9, 0, 123])
  [6, 4, 6, 3, 4, 4, 10, 1, 124]
  */
const incrList = (l) => {

const testIncrList = () => {
  console.assert(JSON.stringify(incrList([])) === JSON.stringify([]))
  console.assert(
    JSON.stringify(incrList([3, 2, 1])) === JSON.stringify([4, 3, 2])
  )
  console.assert(
    JSON.stringify(incrList([5, 2, 5, 2, 3, 3, 9, 0, 123])) ===
      JSON.stringify([6, 3, 6, 3, 4, 4, 10, 1, 124])
  )
}

testIncrList()

const testIncrList = () => {
  console.assert(
    JSON.stringify(incrList([1, 2, 3])) === JSON.stringify([2, 3, 4])
  )
  console.assert(
    JSON.stringify(incrList([5, 2, 5, 2, 3, 3, 9, 0, 123])) ===
      JSON.stringify([6, 3, 6, 3, 4, 4, 10, 1, 124])
  )
}
testIncrList()


Prompt:
/*
  pairsSumToZero takes a list of integers as an input.
  it returns true if there are two distinct elements in the list that
  sum to zero, and false otherwise.
  >>> pairsSumToZero([1, 3, 5, 0])
  false
  >>> pairsSumToZero([1, 3, -2, 1])
  false
  >>> pairsSumToZero([1, 2, 3, 7])
  false
  >>> pairsSumToZero([2, 4, -5, 3, 5, 7])
  true
  >>> pairsSumToZero([1])
  false
  */
const pairsSumToZero = (l) => {

  for (let i = 0; i < l.length; i++)
    for (let j = i + 1; j < l.length; j++)
      if (l[i] + l[j] == 0)
        return true;
  return false;
}

const testPairsSumToZero = () => {
  console.assert(pairsSumToZero([1, 3, 5, 0]) === false)
  console.assert(pairsSumToZero([1, 3, -2, 1]) === false)
  console.assert(pairsSumToZero([1, 2, 3, 7]) === false)
  console.assert(pairsSumToZero([2, 4, -5, 3, 5, 7]) === true)
  console.assert(pairsSumToZero([1]) === false)
  console.assert(pairsSumToZero([-3, 9, -1, 3, 2, 30]) === true)
  console.assert(pairsSumToZero([-3, 9, -1, 3, 2, 31]) === true)
  console.assert(pairsSumToZero([-3, 9, -1, 4, 2, 30]) === false)
  console.assert(pairsSumToZero([-3, 9, -1, 4, 2, 31]) === false)
}

testPairsSumToZero()

const testPairsSumToZero = () => {
  console.assert(pairsSumToZero([1, 3, 5, 0]) === false)
  console.assert(pairsSumToZero([1, 3, -2, 1]) === false)
  console.assert(pairsSumToZero([1, 2, 3, 7]) === false)
  console.assert(pairsSumToZero([2, 4, -5, 3, 5, 7]) === true)
}
testPairsSumToZero()


Prompt:
/*Change numerical base of input number x to base.
  return string representation after the conversion.
  base numbers are less than 10.
  >>> changeBase(8, 3)
  '22'
  >>> changeBase(8, 2)
  '1000'
  >>> changeBase(7, 2)
  '111'
  */
const changeBase = (x, base) => {

  var ret = "";
  while (x > 0) {
    ret = (x % base).toString() + ret;
    x = Math.floor(x / base);
  }
  return ret;
}

const testChangeBase = () => {
  console.assert(changeBase(8, 3) === '22')
  console.assert(changeBase(9, 3) === '100')
  console.assert(changeBase(234, 2) === '11101010')
  console.assert(changeBase(16, 2) === '10000')
  console.assert(changeBase(8, 2) === '1000')
  console.assert(changeBase(7, 2) === '111')

  for (let i = 2; i < 8; i++) {
    console.assert(changeBase(i, i + 1) === i.toString())
  }
}

testChangeBase()

const testChangeBase = () => {
  console.assert(changeBase(8, 3) === '22')
  console.assert(changeBase(8, 2) === '1000')
  console.assert(changeBase(7, 2) === '111')
}
testChangeBase()


Prompt:
/*Given length of a side and high return area for a triangle.
  >>> triangleArea(5, 3)
  7.5
  */
const triangleArea = (a, h) => {

const testTriangleArea = () => {
  console.assert(triangleArea(5, 3) === 7.5)
  console.assert(triangleArea(2, 2) === 2.0)
  console.assert(triangleArea(10, 8) === 40.0)
}

testTriangleArea()

const testTriangleArea = () => {
  console.assert(triangleArea(5, 3) === 7.5)
}
testTriangleArea()


Prompt:
/*The Fib4 number sequence is a sequence similar to the Fibbonacci sequnece that's defined as follows:
  fib4(0) -> 0
  fib4(1) -> 0
  fib4(2) -> 2
  fib4(3) -> 0
  fib4(n) -> fib4(n-1) + fib4(n-2) + fib4(n-3) + fib4(n-4).
  Please write a function to efficiently compute the n-th element of the fib4 number sequence.  Do not use recursion.
  >>> fib4(5)
  4
  >>> fib4(6)
  8
  >>> fib4(7)
  14
  */
const fib4 = (n) => {

  var results = [0, 0, 2, 0];
  if (n < 4)
    return results[n];
  for (let i = 4; i < n + 1; i++) {
    results.push(results.at(-1) + results.at(-2) +
                results.at(-3) + results.at(-4));
    results.shift();
  }
  return results.pop();
}

const testFib4 = () => {
  console.assert(fib4(5) === 4)
  console.assert(fib4(8) === 28)
  console.assert(fib4(10) === 104)
  console.assert(fib4(12) === 386)
}

testFib4()

const testFib4 = () => {
  console.assert(fib4(5) === 4)
  console.assert(fib4(6) === 8)
  console.assert(fib4(7) === 14)
}
testFib4()


Prompt:
/*Return median of elements in the list l.
  >>> median([3, 1, 2, 4, 5])
  3
  >>> median([-10, 4, 6, 1000, 10, 20])
  8.0
  */
const median = (l) => {

  l.sort((a, b) => a - b);
  var len = l.length;
  if (l.length % 2 == 1)
    return l[Math.floor(len / 2)];
  else
    return (l[len / 2 - 1] + l[len / 2]) / 2.0;
}

const testMedian = () => {
  console.assert(median([3, 1, 2, 4, 5]) === 3)
  console.assert(median([-10, 4, 6, 1000, 10, 20]) === 8.0)
  console.assert(median([5]) === 5)
  console.assert(median([6, 5]) === 5.5)
  console.assert(median([8, 1, 3, 9, 9, 2, 7]) === 7)
}

testMedian()

const testMedian = () => {
  console.assert(median([3, 1, 2, 4, 5]) === 3)
  console.assert(median([-10, 4, 6, 1000, 10, 20]) === 8.0)
}
testMedian()


Prompt:
/*
  Checks if given string is a palindrome
  >>> isPalindrome('')
  true
  >>> isPalindrome('aba')
  true
  >>> isPalindrome('aaaaa')
  true
  >>> isPalindrome('zbcd')
  false
  */
const isPalindrome = (text) => {

  for (let i = 0; i < text.length; i++)
    if (text[i] != text.at(-i-1))
      return false;
  return true;
}

const testIsPalindrome = () => {
  console.assert(isPalindrome('') === true)
  console.assert(isPalindrome('aba') === true)
  console.assert(isPalindrome('aaaaa') === true)
  console.assert(isPalindrome('zbcd') === false)
  console.assert(isPalindrome('xywyx') === true)
  console.assert(isPalindrome('xywyz') === false)
  console.assert(isPalindrome('xywzx') === false)
}

testIsPalindrome()

const testIsPalindrome = () => {
  console.assert(isPalindrome('') === true)
  console.assert(isPalindrome('aba') === true)
  console.assert(isPalindrome('aaaaa') === true)
  console.assert(isPalindrome('zbcd') === false)
}
testIsPalindrome()


Prompt:
/*Return 2^n modulo p (be aware of numerics).
  >>> modp(3, 5)
  3
  >>> modp(1101, 101)
  2
  >>> modp(0, 101)
  1
  >>> modp(3, 11)
  8
  >>> modp(100, 101)
  1
  */
const modp = (n, p) => {

  var ret = 1;
  for (let i = 0; i < n; i++)
    ret = (2 * ret) % p;
  return ret;
}

const testModp = () => {
  console.assert(modp(3, 5) === 3)
  console.assert(modp(1101, 101) === 2)
  console.assert(modp(0, 101) === 1)
  console.assert(modp(3, 11) === 8)
  console.assert(modp(100, 101) === 1)
  console.assert(modp(30, 5) === 4)
  console.assert(modp(31, 5) === 3)
}

testModp()

const testModp = () => {
  console.assert(modp(3, 5) === 3)
  console.assert(modp(1101, 101) === 2)
  console.assert(modp(0, 101) === 1)
  console.assert(modp(3, 11) === 8)
  console.assert(modp(100, 101) === 1)
}
testModp()


Prompt:
/*
  returns encoded string by shifting every character by 5 in the alphabet.
  */
const encodeShift = (s) => {
  return s.split("").map(ch => String.fromCharCode(
    ((ch.charCodeAt(0) + 5 - "a".charCodeAt(0)) % 26) + "a".charCodeAt(0)
  )).join("");
}

/*
  takes as input string encoded with encode_shift function. Returns decoded string.
  */
const decodeShift = (s) => {

  return s.split("").map(ch => String.fromCharCode(
    ((ch.charCodeAt(0) - 5 + 26 - "a".charCodeAt(0)) % 26) + "a".charCodeAt(0)
  )).join("");
}

const testDecodeShift = () => {
    const letters = new Array(26)
    .fill(null)
    .map((v, i) => String.fromCharCode(97 + i))

    for (let i = 0; i < 100; i++) {
      let str = new Array(Math.floor(Math.random() * 20)).fill(null);
      str = str.map(item => letters[Math.floor(Math.random() * letters.length)]).join('');
      let encoded_str = encodeShift(str)
      console.assert(decodeShift(encoded_str) === str)
    }

}

testDecodeShift()

const encodeShift = (s) => {
  return s.split("").map(ch => String.fromCharCode(
    ((ch.charCodeAt(0) + 5 - "a".charCodeAt(0)) % 26) + "a".charCodeAt(0)
  )).join("");
}

const decodeShift = (s) => {


Prompt:
/*
  removeVowels is a function that takes string and returns string without vowels.
  >>> removeVowels('')
  ''
  >>> removeVowels("abcdef\nghijklm")
  'bcdf\nghjklm'
  >>> removeVowels('abcdef')
  'bcdf'
  >>> removeVowels('aaaaa')
  ''
  >>> removeVowels('aaBAA')
  'B'
  >>> removeVowels('zbcd')
  'zbcd'
  */
const removeVowels = (text) => {

  return text.split("")
             .filter(s => !["a", "e", "i", "o", "u"]
                      .includes(s.toLowerCase())
                    )
             .join("")
}

const testRemoveVowels = () => {
  console.assert(removeVowels('') === '')
  console.assert(removeVowels('abcdef\nghijklm') === 'bcdf\nghjklm')
  console.assert(removeVowels('fedcba') === 'fdcb')
  console.assert(removeVowels('eeeee') === '')
  console.assert(removeVowels('acBAA') === 'cB')
  console.assert(removeVowels('EcBOO') === 'cB')
  console.assert(removeVowels('ybcd') === 'ybcd')
}

testRemoveVowels()

const testRemoveVowels = () => {
  console.assert(removeVowels('') === '')
  console.assert(removeVowels('abcdef\nghijklm') === 'bcdf\nghjklm')
  console.assert(removeVowels('abcdef') === 'bcdf')
  console.assert(removeVowels('aaaaa') === '')
  console.assert(removeVowels('aaBAA') === 'B')
  console.assert(removeVowels('zbcd') === 'zbcd')
}
testRemoveVowels()


Prompt:
/*Return true if all numbers in the list l are below threshold t.
  >>> belowThreshold([1, 2, 4, 10], 100)
  true
  >>> belowThreshold([1, 20, 4, 10], 5)
  false
  */
const belowThreshold = (l, t) => {

  for (const e of l)
    if (e >= t)
      return false;
  return true;
}

const testBelowThreshold = () => {
  console.assert(belowThreshold([1, 2, 4, 10], 100) === true)
  console.assert(belowThreshold([1, 20, 4, 10], 5) === false)
  console.assert(belowThreshold([1, 20, 4, 10], 21) === true)
  console.assert(belowThreshold([1, 20, 4, 10], 22) === true)
  console.assert(belowThreshold([1, 8, 4, 10], 11) === true)
  console.assert(belowThreshold([1, 8, 4, 10], 10) === false)
}

testBelowThreshold()

const testBelowThreshold = () => {
  console.assert(belowThreshold([1, 2, 4, 10], 100) === true)
  console.assert(belowThreshold([1, 20, 4, 10], 5) === false)
}
testBelowThreshold()


Prompt:
/*Add two numbers x and y
  >>> add(2, 3)
  5
  >>> add(5, 7)
  12
  */
const add = (x, y) => {

const testAdd = () => {
  const getRandomIntInclusive = (min = 0, max = 9) => {
    min = Math.ceil(min)
    max = Math.floor(max)
    return Math.floor(Math.random() * (max - min + 1)) + min //含最大值，含最小值
  }

  console.assert(add(0, 1) === 1)
  console.assert(add(1, 0) === 1)
  console.assert(add(2, 3) === 5)
  console.assert(add(5, 7) === 12)
  console.assert(add(7, 5) === 12)

  for (let i = 0; i < 100; i++) {
    let x = getRandomIntInclusive()
    let y = getRandomIntInclusive()
    console.assert(x + y === add(x, y))
  }
}

testAdd()

const testAdd = () => {
  const getRandomIntInclusive = (min = 0, max = 9) => {
    min = Math.ceil(min)
    max = Math.floor(max)
    return Math.floor(Math.random() * (max - min + 1)) + min //含最大值，含最小值
  }
  console.assert(add(2, 3) === 5)
  console.assert(add(5, 7) === 12)
}
testAdd()


Prompt:
/*
  Check if two words have the same characters.
  >>> sameChars('eabcdzzzz', 'dddzzzzzzzddeddabc')
  true
  >>> sameChars('abcd', 'dddddddabc')
  true
  >>> sameChars('dddddddabc', 'abcd')
  true
  >>> sameChars('eabcd', 'dddddddabc')
  false
  >>> sameChars('abcd', 'dddddddabce')
  false
  >>> sameChars('eabcdzzzz', 'dddzzzzzzzddddabc')
  false
  */
const sameChars = (s0, s1) => {

  return JSON.stringify([...new Set(s0)].sort()) === JSON.stringify([...new Set(s1)].sort());
}

const testSameChars = () => {
  console.assert(sameChars('eabcdzzzz', 'dddzzzzzzzddeddabc') === true)
  console.assert(sameChars('abcd', 'dddddddabc') === true)
  console.assert(sameChars('dddddddabc', 'abcd') === true)
  console.assert(sameChars('eabcd', 'dddddddabc') === false)
  console.assert(sameChars('abcd', 'dddddddabcf') === false)
  console.assert(sameChars('eabcdzzzz', 'dddzzzzzzzddddabc') === false)
  console.assert(sameChars('aabb', 'aaccc') === false)
}

testSameChars()

const testSameChars = () => {
  console.assert(sameChars('eabcdzzzz', 'dddzzzzzzzddeddabc') === true)
  console.assert(sameChars('abcd', 'dddddddabc') === true)
  console.assert(sameChars('dddddddabc', 'abcd') === true)
  console.assert(sameChars('eabcd', 'dddddddabc') === false)
  console.assert(sameChars('abcd', 'dddddddabcf') === false)
  console.assert(sameChars('eabcdzzzz', 'dddzzzzzzzddddabc') === false)
}
testSameChars()


Prompt:
/*Return n-th Fibonacci number.
  >>> fib(10)
  55
  >>> fib(1)
  1
  >>> fib(8)
  21
  */
const fib = (n) => {

  if (n == 0)
    return 0;
  if (n == 1)
    return 1;
  return fib(n - 1) + fib(n - 2);
}

const testFib = () => {
  console.assert(fib(10) === 55)
  console.assert(fib(1) === 1)
  console.assert(fib(8) === 21)
  console.assert(fib(11) === 89)
  console.assert(fib(12) === 144)
}

testFib()

const testFib = () => {
  console.assert(fib(10) === 55)
  console.assert(fib(1) === 1)
  console.assert(fib(8) === 21)
}
testFib()


Prompt:
/* brackets is a string of "<" and ">".
  return false if every opening bracket has a corresponding closing bracket.

  >>> correctBracketing("<")
  false
  >>> correctBracketing("<>")
  false
  >>> correctBracketing("<<><>>")
  false
  >>> correctBracketing("><<>")
  false
  */
const correctBracketing = (brackets) => {

  var depth = 0;
  for (const b of brackets) {
    if (b == "<")
      depth += 1;
    else
      depth -= 1;
    if (depth < 0)
      return false;
  }
  return depth == 0;
}

const testCorrectBracketing = () => {
  console.assert(correctBracketing('<>') === true)
  console.assert(correctBracketing('<<><>>') === true)
  console.assert(correctBracketing('<><><<><>><>') === true)
  console.assert(correctBracketing('<><><<<><><>><>><<><><<>>>') === true)
  console.assert(correctBracketing('<<<><>>>>') === false)
  console.assert(correctBracketing('><<>') === false)
  console.assert(correctBracketing('<') === false)
  console.assert(correctBracketing('<<<<') === false)
  console.assert(correctBracketing('>') === false)
  console.assert(correctBracketing('<<>') === false)
  console.assert(correctBracketing('<><><<><>><>><<>') === false)
  console.assert(correctBracketing('<><><<><>><>>><>') === false)
}

testCorrectBracketing()

const testCorrectBracketing = () => {
  console.assert(correctBracketing('<>') === true)
  console.assert(correctBracketing('<<><>>') === true)
  console.assert(correctBracketing('><<>') === false)
  console.assert(correctBracketing('<') === false)
}
testCorrectBracketing()


Prompt:
/*Return true is list elements are monotonically increasing or decreasing.
  >>> monotonic([1, 2, 4, 20])
  true
  >>> monotonic([1, 20, 4, 10])
  false
  >>> monotonic([4, 1, 0, -10])
  true
  */
const monotonic = (l) => {

  var sort1 = [...l].sort((a, b) => a - b);
  var sort2 = [...l].sort((a, b) => b - a);
  if (JSON.stringify(l) === JSON.stringify(sort1) ||
      JSON.stringify(l) === JSON.stringify(sort2))
    return true;
  return false;
}

const testMonotonic = () => {
  console.assert(monotonic([1, 2, 4, 10]) === true)
  console.assert(monotonic([1, 2, 4, 20]) === true)
  console.assert(monotonic([1, 20, 4, 10]) === false)
  console.assert(monotonic([4, 1, 0, -10]) === true)
  console.assert(monotonic([4, 1, 1, 0]) === true)
  console.assert(monotonic([1, 2, 3, 2, 5, 60]) === false)
  console.assert(monotonic([1, 2, 3, 4, 5, 60]) === true)
  console.assert(monotonic([9, 9, 9, 9]) === true)
}

testMonotonic()

const testMonotonic = () => {
  console.assert(monotonic([1, 2, 4, 10]) === true)
  console.assert(monotonic([1, 20, 4, 10]) === false)
  console.assert(monotonic([4, 1, 0, -10]) === true)
}
testMonotonic()


Prompt:
/*Return sorted unique common elements for two lists.
  >>> common([1, 4, 3, 34, 653, 2, 5], [5, 7, 1, 5, 9, 653, 121])
  [1, 5, 653]
  >>> common([5, 3, 2, 8], [3, 2])
  [2, 3]

  */
const common = (l1, l2) => {

  var ret = new Set();
  for (const e1 of l1)
    for (const e2 of l2)
      if (e1 == e2)
        ret.add(e1);
  return [...ret].sort();
}

const testCommon = () => {
  console.assert(
    JSON.stringify(common([1, 4, 3, 34, 653, 2, 5], [5, 7, 1, 5, 9, 653, 121]))
     === JSON.stringify([1, 5, 653])
  )
  console.assert(
    JSON.stringify(common([5, 3, 2, 8], [3, 2]))
     === JSON.stringify([2, 3])
  )
  console.assert(
    JSON.stringify(common([4, 3, 2, 8], [3, 2, 4])) ===
      JSON.stringify([2, 3, 4])
  )
  console.assert(
    JSON.stringify(common([4, 3, 2, 8], [])) === JSON.stringify([])
  )
}

testCommon()

const testCommon = () => {
  console.assert(
    JSON.stringify(common([1, 4, 3, 34, 653, 2, 5], [5, 7, 1, 5, 9, 653, 121]))
     === JSON.stringify([1, 5, 653])
  )
  console.assert(
    JSON.stringify(common([5, 3, 2, 8], [3, 2]))
     === JSON.stringify([2, 3])
  )
}
testCommon()


Prompt:
/*Return the largest prime factor of n. Assume n > 1 and is not a prime.
  >>> largestPrimeFactor(13195)
  29
  >>> largestPrimeFactor(2048)
  2
  */
const largestPrimeFactor = (n) => {

  var isPrime = function (k) {
    if (k < 2)
      return false;
    for (let i = 2; i < k - 1; i++)
      if (k % i == 0)
        return false;
    return true;
  }

  var largest = 1;
  for (let j = 2; j < n + 1; j++)
    if (n % j == 0 && isPrime(j))
      largest = Math.max(largest, j);
  return largest;
}

const testLargestPrimeFactor = () => {
  console.assert(largestPrimeFactor(15) === 5)
  console.assert(largestPrimeFactor(27) === 3)
  console.assert(largestPrimeFactor(63) === 7)
  console.assert(largestPrimeFactor(330) === 11)
  console.assert(largestPrimeFactor(13195) === 29)
}

testLargestPrimeFactor()

const testLargestPrimeFactor = () => {
  console.assert(largestPrimeFactor(2048) === 2)
  console.assert(largestPrimeFactor(13195) === 29)
}
testLargestPrimeFactor()


Prompt:
/*sumToN is a function that sums numbers from 1 to n.
  >>> sumToN(30)
  465
  >>> sumToN(100)
  5050
  >>> sumToN(5)
  15
  >>> sumToN(10)
  55
  >>> sumToN(1)
  1
  */
const sumToN = (n) => {

const testSumToN = () => {
  console.assert(sumToN(1) === 1)
  console.assert(sumToN(6) === 21)
  console.assert(sumToN(11) === 66)
  console.assert(sumToN(30) === 465)
  console.assert(sumToN(100) === 5050)
}

testSumToN()

const testSumToN = () => {
  console.assert(sumToN(1) === 1)
  console.assert(sumToN(5) === 15)
  console.assert(sumToN(10) === 55)
  console.assert(sumToN(30) === 465)
  console.assert(sumToN(100) === 5050)
}
testSumToN()


Prompt:
/* brackets is a string of "(" and ")".
  return true if every opening bracket has a corresponding closing bracket.

  >>> correctBracketing("(")
  false
  >>> correctBracketing("()")
  true
  >>> correctBracketing("(()())")
  true
  >>> correctBracketing(")(()")
  false
  */
const correctBracketing = (brackets) => {

  var depth = 0;
  for (const b of brackets) {
    if (b == "(")
      depth += 1;
    else
      depth -= 1;
    if (depth < 0)
      return false;
  }
  return depth == 0;
}

const testCorrectBracketing = () => {
  console.assert(correctBracketing('()') === true)
  console.assert(correctBracketing('(()())') === true)
  console.assert(correctBracketing('()()(()())()') === true)
  console.assert(correctBracketing('()()((()()())())(()()(()))') === true)
  console.assert(correctBracketing('((()())))') === false)
  console.assert(correctBracketing(')(()') === false)
  console.assert(correctBracketing('(') === false)
  console.assert(correctBracketing('((((') === false)
  console.assert(correctBracketing(')') === false)
  console.assert(correctBracketing('(()') === false)
  console.assert(correctBracketing('()()(()())())(()') === false)
  console.assert(correctBracketing('()()(()())()))()') === false)
}

testCorrectBracketing()

const testCorrectBracketing = () => {
  console.assert(correctBracketing('()') === true)
  console.assert(correctBracketing('(()())') === true)
  console.assert(correctBracketing(')(()') === false)
  console.assert(correctBracketing('(') === false)
}
testCorrectBracketing()


Prompt:
/* xs represent coefficients of a polynomial.
  xs[0] + xs[1] * x + xs[2] * x^2 + ....
   Return derivative of this polynomial in the same form.
  >>> derivative([3, 1, 2, 4, 5])
  [1, 4, 12, 20]
  >>> derivative([1, 2, 3])
  [2, 6]
  */
const derivative = (xs) => {

  return xs.map((x, i) => x * i).slice(1);
}

const testDerivative = () => {
  console.assert(
    JSON.stringify(derivative([3, 1, 2, 4, 5])) ===
      JSON.stringify([1, 4, 12, 20])
  )
  console.assert(
    JSON.stringify(derivative([1, 2, 3])) === JSON.stringify([2, 6])
  )
  console.assert(
    JSON.stringify(derivative([3, 2, 1])) === JSON.stringify([2, 2])
  )
  console.assert(
    JSON.stringify(derivative([3, 2, 1, 0, 4])) ===
      JSON.stringify([2, 2, 0, 16])
  )
  console.assert(JSON.stringify(derivative([1])) === JSON.stringify([]))
}

testDerivative()

const testDerivative = () => {
  console.assert(
    JSON.stringify(derivative([3, 1, 2, 4, 5])) ===
      JSON.stringify([1, 4, 12, 20])
  )
  console.assert(
    JSON.stringify(derivative([1, 2, 3])) === JSON.stringify([2, 6])
  )
}
testDerivative()


Prompt:
/*The FibFib number sequence is a sequence similar to the Fibbonacci sequnece that's defined as follows:
  fibfib(0) == 0
  fibfib(1) == 0
  fibfib(2) == 1
  fibfib(n) == fibfib(n-1) + fibfib(n-2) + fibfib(n-3).
  Please write a function to efficiently compute the n-th element of the fibfib number sequence.
  >>> fibfib(1)
  0
  >>> fibfib(5)
  4
  >>> fibfib(8)
  24
  */
const fibfib = (n) => {

  if (n == 0 || n == 1)
    return 0;
  if (n == 2)
    return 1;
  return fibfib(n - 1) + fibfib(n - 2) + fibfib(n - 3);
}

const testFibfib = () => {
  console.assert(fibfib(2) === 1)
  console.assert(fibfib(1) === 0)
  console.assert(fibfib(5) === 4)
  console.assert(fibfib(8) === 24)
  console.assert(fibfib(10) === 81)
  console.assert(fibfib(12) === 274)
  console.assert(fibfib(14) === 927)
}

testFibfib()

const testFibfib = () => {
  console.assert(fibfib(1) === 0)
  console.assert(fibfib(5) === 4)
  console.assert(fibfib(8) === 24)
}
testFibfib()


Prompt:
/*Write a function vowelsCount which takes a string representing
  a word as input and returns the number of vowels in the string.
  Vowels in this case are 'a', 'e', 'i', 'o', 'u'. Here, 'y' is also a
  vowel, but only when it is at the end of the given word.

  Example:
  >>> vowelsCount("abcde")
  2
  >>> vowelsCount("ACEDY")
  3
  */
const vowelsCount = (s) => {

  var vowels = "aeiouAEIOU";
  var n_vowels = s.split('').reduce((prev, item) => {
    return prev + (vowels.includes(item));
  }, 0);
  if (s.at(-1) == 'y' || s.at(-1) == 'Y')
    n_vowels += 1;
  return n_vowels;
}

const testVowelsCount = () => {
  console.assert(vowelsCount('abcde') === 2)
  console.assert(vowelsCount('Alone') === 3)
  console.assert(vowelsCount('key') === 2)
  console.assert(vowelsCount('bye') === 1)
  console.assert(vowelsCount('keY') === 2)
  console.assert(vowelsCount('bYe') === 1)
  console.assert(vowelsCount('ACEDY') === 3)
}

testVowelsCount()

const testVowelsCount = () => {
  console.assert(vowelsCount('abcde') === 2)
  console.assert(vowelsCount('ACEDY') === 3)
}
testVowelsCount()


Prompt:
/*Circular shift the digits of the integer x, shift the digits right by shift
  and return the result as a string.
  If shift > number of digits, return digits reversed.
  >>> circularShift(12, 1)
  "21"
  >>> circularShift(12, 2)
  "12"
  */
const circularShift = (x, shift) => {

  s = x.toString();
  if (shift > s.length)
    return s.split('').reverse().join('');
  else
    return s.slice(-shift) + s.slice(0, -shift);
}

const testCircularShift = () => {
  console.assert(circularShift(100, 2) === '001')
  console.assert(circularShift(12, 2) === '12')
  console.assert(circularShift(97, 8) === '79')
  console.assert(circularShift(12, 1) === '21')
  console.assert(circularShift(11, 101) === '11')
}

testCircularShift()

const testCircularShift = () => {
  console.assert(circularShift(12, 2) === '12')
  console.assert(circularShift(12, 1) === '21')
}
testCircularShift()


Prompt:
/*Task
  Write a function that takes a string as input and returns the sum of the upper characters only'
  ASCII codes.

  Examples:
      digitSum("") => 0
      digitSum("abAB") => 131
      digitSum("abcCd") => 67
      digitSum("helloE") => 69
      digitSum("woArBld") => 131
      digitSum("aAaaaXa") => 153
  */
const digitSum = (s) => {

  if (s == '') return 0;
  return s.split('').reduce((prev, char) => {
    let ord_char = char.charCodeAt(0)
    return prev + (ord_char > 64 && ord_char < 91 ? ord_char : 0);
  }, 0);
}

const testDigitSum = () => {
  console.assert(digitSum('') === 0)
  console.assert(digitSum('abAB') === 131)
  console.assert(digitSum('abcCd') === 67)
  console.assert(digitSum('helloE') === 69)
  console.assert(digitSum('woArBld') === 131)
  console.assert(digitSum('aAaaaXa') === 153)
  console.assert(digitSum(' How are yOu?') === 151)
  console.assert(digitSum('You arE Very Smart') === 327)
}

testDigitSum()

const testDigitSum = () => {
  console.assert(digitSum('') === 0)
  console.assert(digitSum('abAB') === 131)
  console.assert(digitSum('abcCd') === 67)
  console.assert(digitSum('helloE') === 69)
  console.assert(digitSum('woArBld') === 131)
  console.assert(digitSum('aAaaaXa') === 153)
}
testDigitSum()


Prompt:
/*
  In this task, you will be given a string that represents a number of apples and oranges
  that are distributed in a basket of fruit this basket contains
  apples, oranges, and mango fruits. Given the string that represents the total number of
  the oranges and apples and an integer that represent the total number of the fruits
  in the basket return the number of the mango fruits in the basket.
  for examble:
  fruitDistribution("5 apples and 6 oranges", 19) ->19 - 5 - 6 = 8
  fruitDistribution("0 apples and 1 oranges",3) -> 3 - 0 - 1 = 2
  fruitDistribution("2 apples and 3 oranges", 100) -> 100 - 2 - 3 = 95
  fruitDistribution("100 apples and 1 oranges",120) -> 120 - 100 - 1 = 19
  */
const fruitDistribution = (s, n) => {

  var lis = [];
  for (const i of s.split(" "))
    if (!isNaN(i))
      lis.push(Number(i))
  return n - lis.reduce(((prev, item) => prev + item), 0);
}

const testFruitDistribution = () => {
  console.assert(fruitDistribution('5 apples and 6 oranges', 19) === 8)
  console.assert(fruitDistribution('5 apples and 6 oranges', 21) === 10)
  console.assert(fruitDistribution('0 apples and 1 oranges', 3) === 2)
  console.assert(fruitDistribution('1 apples and 0 oranges', 3) === 2)
  console.assert(fruitDistribution('2 apples and 3 oranges', 100) === 95)
  console.assert(fruitDistribution('2 apples and 3 oranges', 5) === 0)
  console.assert(fruitDistribution('1 apples and 100 oranges', 120) === 19)
}

testFruitDistribution()

const testFruitDistribution = () => {
  console.assert(fruitDistribution('5 apples and 6 oranges', 19) === 8)
  console.assert(fruitDistribution('0 apples and 1 oranges', 3) === 2)
  console.assert(fruitDistribution('2 apples and 3 oranges', 100) === 95)
  console.assert(fruitDistribution('1 apples and 100 oranges', 120) === 19)
}
testFruitDistribution()


Prompt:
/*
  "Given an array representing a branch of a tree that has non-negative integer nodes
  your task is to pluck one of the nodes and return it.
  The plucked node should be the node with the smallest even value.
  If multiple nodes with the same smallest even value are found return the node that has smallest index.

  The plucked node should be returned in a list, [ smalest_value, its index ],
  If there are no even values or the given array is empty, return [].

  Example 1:
      Input: [4,2,3]
      Output: [2, 1]
      Explanation: 2 has the smallest even value, and 2 has the smallest index.

  Example 2:
      Input: [1,2,3]
      Output: [2, 1]
      Explanation: 2 has the smallest even value, and 2 has the smallest index.

  Example 3:
      Input: []
      Output: []

  Example 4:
      Input: [5, 0, 3, 0, 4, 2]
      Output: [0, 1]
      Explanation: 0 is the smallest value, but  there are two zeros,
                   so we will choose the first zero, which has the smallest index.

  Constraints:
      * 1 <= nodes.length <= 10000
      * 0 <= node.value
  */
const pluck = (arr) => {

  if (arr.length == 0) return [];
  var evens = arr.filter(x => x % 2 == 0);
  if (evens.length == 0) return [];
  return [Math.min(...evens), arr.indexOf(Math.min(...evens))];
}

const testPluck = () => {
  console.assert(JSON.stringify(pluck([4, 2, 3])) === JSON.stringify([2, 1]))
  console.assert(JSON.stringify(pluck([1, 2, 3])) === JSON.stringify([2, 1]))
  console.assert(JSON.stringify(pluck([])) === JSON.stringify([]))
  console.assert(
    JSON.stringify(pluck([5, 0, 3, 0, 4, 2])) === JSON.stringify([0, 1])
  )
  console.assert(
    JSON.stringify(pluck([1, 2, 3, 0, 5, 3])) === JSON.stringify([0, 3])
  )
  console.assert(
    JSON.stringify(pluck([5, 4, 8, 4, 8])) === JSON.stringify([4, 1])
  )
  console.assert(JSON.stringify(pluck([7, 6, 7, 1])) === JSON.stringify([6, 1]))
  console.assert(JSON.stringify(pluck([7, 9, 7, 1])) === JSON.stringify([]))
}

testPluck()

const testPluck = () => {
  console.assert(JSON.stringify(pluck([4, 2, 3])) === JSON.stringify([2, 1]))
  console.assert(JSON.stringify(pluck([1, 2, 3])) === JSON.stringify([2, 1]))
  console.assert(JSON.stringify(pluck([])) === JSON.stringify([]))
  console.assert(
    JSON.stringify(pluck([5, 0, 3, 0, 4, 2])) === JSON.stringify([0, 1])
  )
}
testPluck()


Prompt:
/*
  You are given a non-empty list of positive integers. Return the greatest integer that is greater than
  zero, and has a frequency greater than or equal to the value of the integer itself.
  The frequency of an integer is the number of times it appears in the list.
  If no such a value exist, return -1.
  Examples:
      search([4, 1, 2, 2, 3, 1])) == 2
      search([1, 2, 2, 3, 3, 3, 4, 4, 4])) == 3
      search([5, 5, 4, 4, 4])) == -1
  */
const search = (lst) => {

  var frq = new Array(Math.max(...lst) + 1).fill(0);
  for (const i of lst)
    frq[i] += 1;
  var ans = -1;
  for (let i = 1; i < frq.length; i++)
    if (frq[i] >= i)
      ans = i;
  return ans;
}

const testSearch = () => {
  console.assert(search([4, 1, 2, 2, 3, 1]) === 2)
  console.assert(search([1, 2, 2, 3, 3, 3, 4, 4, 4]) === 3)
  console.assert(search([5, 5, 4, 4, 4]) === -1)
}
testSearch()


Prompt:
/*
  Given list of integers, return list in strange order.
  Strange sorting, is when you start with the minimum value,
  then maximum of the remaining integers, then minimum and so on.

  Examples:
  strangeSortList([1, 2, 3, 4]) == [1, 4, 2, 3]
  strangeSortList([5, 5, 5, 5]) == [5, 5, 5, 5]
  strangeSortList([]) == []
  */
const strangeSortList = (lst) => {

  var res = [], sw = true;
  while (lst.length) {
    res.push(sw ? Math.min(...lst) : Math.max(...lst));
    lst.splice(lst.indexOf(res.at(-1)), 1);
    sw = !sw;
  }
  return res;
}

const testStrangeSortList = () => {
  console.assert(
    JSON.stringify(strangeSortList([1, 2, 3, 4])) ===
      JSON.stringify([1, 4, 2, 3])
  )
  console.assert(
    JSON.stringify(strangeSortList([5, 6, 7, 8, 9])) ===
      JSON.stringify([5, 9, 6, 8, 7])
  )
  console.assert(
    JSON.stringify(strangeSortList([1, 2, 3, 4, 5])) ===
      JSON.stringify([1, 5, 2, 4, 3])
  )
  console.assert(
    JSON.stringify(strangeSortList([5, 6, 7, 8, 9, 1])) ===
      JSON.stringify([1, 9, 5, 8, 6, 7])
  )
  console.assert(
    JSON.stringify(strangeSortList([5, 5, 5, 5])) ===
      JSON.stringify([5, 5, 5, 5])
  )
  console.assert(JSON.stringify(strangeSortList([])) === JSON.stringify([]))
  console.assert(
    JSON.stringify(strangeSortList([1, 2, 3, 4, 5, 6, 7, 8])) ===
      JSON.stringify([1, 8, 2, 7, 3, 6, 4, 5])
  )
  console.assert(
    JSON.stringify(strangeSortList([0, 2, 2, 2, 5, 5, -5, -5])) ===
      JSON.stringify([-5, 5, -5, 5, 0, 2, 2, 2])
  )
  console.assert(
    JSON.stringify(strangeSortList([111111])) === JSON.stringify([111111])
  )
}

testStrangeSortList()

const testStrangeSortList = () => {
  console.assert(
    JSON.stringify(strangeSortList([1, 2, 3, 4])) ===
      JSON.stringify([1, 4, 2, 3])
  )
  console.assert(
    JSON.stringify(strangeSortList([5, 5, 5, 5])) ===
      JSON.stringify([5, 5, 5, 5])
  )
  console.assert(JSON.stringify(strangeSortList([])) === JSON.stringify([]))
}
testStrangeSortList()


Prompt:
/*
  Given the lengths of the three sides of a triangle. Return the area of
  the triangle rounded to 2 decimal points if the three sides form a valid triangle.
  Otherwise return -1
  Three sides make a valid triangle when the sum of any two sides is greater
  than the third side.
  Example:
  triangleArea(3, 4, 5) == 6.00
  triangleArea(1, 2, 10) == -1
  */
const triangleArea = (a, b, c) => {

  if (a + b <= c || a + c <= b || b + c <= a)
    return -1;
  var s = (a + b + c) / 2;
  var area = Math.pow(s * (s - a) * (s - b) * (s - c), 0.5);
  area = area.toFixed(2);
  return area;
}

const testTriangleArea = () => {
  console.assert(triangleArea(3, 4, 5) == 6.0)
  console.assert(triangleArea(1, 2, 10) == -1)
  console.assert(triangleArea(4, 8, 5) == 8.18)
  console.assert(triangleArea(2, 2, 2) == 1.73)
  console.assert(triangleArea(1, 2, 3) == -1)
  console.assert(triangleArea(10, 5, 7) == 16.25)
  console.assert(triangleArea(2, 6, 3) == -1)
  console.assert(triangleArea(1, 1, 1) == 0.43)
  console.assert(triangleArea(2, 2, 10) == -1)
}

testTriangleArea()

const testTriangleArea = () => {
  console.assert(triangleArea(3, 4, 5) == 6.0)
  console.assert(triangleArea(1, 2, 10) == -1)
}
testTriangleArea()


Prompt:
/*
  Write a function that returns true if the object q will fly, and false otherwise.
  The object q will fly if it's balanced (it is a palindromic list) and the sum of its elements is less than or equal the maximum possible weight w.

  Example:
  willItFly([1, 2], 5) ➞ false
  # 1+2 is less than the maximum possible weight, but it's unbalanced.

  willItFly([3, 2, 3], 1) ➞ false
  # it's balanced, but 3+2+3 is more than the maximum possible weight.

  willItFly([3, 2, 3], 9) ➞ true
  # 3+2+3 is less than the maximum possible weight, and it's balanced.

  willItFly([3], 5) ➞ true
  # 3 is less than the maximum possible weight, and it's balanced.
  */
const willItFly = (q, w) => {

  if (q.reduce(((prev, item) => prev + item), 0) > w)
    return false;
  var i = 0, j = q.length - 1;
  while (i < j) {
    if (q[i] != q[j])
      return false;
    i++;
    j--;
  }
  return true;
}

const testWillItFly = () => {
  console.assert(willItFly([3, 2, 3], 9) === true)
  console.assert(willItFly([1, 2], 5) === false)
  console.assert(willItFly([3], 5) === true)
  console.assert(willItFly([3, 2, 3], 1) === false)
  console.assert(willItFly([1, 2, 3], 6) === false)
  console.assert(willItFly([5], 5) === true)
}

testWillItFly()

const testWillItFly = () => {
  console.assert(willItFly([3, 2, 3], 9) === true)
  console.assert(willItFly([1, 2], 5) === false)
  console.assert(willItFly([3], 5) === true)
  console.assert(willItFly([3, 2, 3], 1) === false)
}
testWillItFly()


Prompt:
/*
  Given an array arr of integers, find the minimum number of elements that
  need to be changed to make the array palindromic. A palindromic array is an array that
  is read the same backwards and forwards. In one change, you can change one element to any other element.

  For example:
  smallestChange([1,2,3,5,4,7,9,6]) == 4
  smallestChange([1, 2, 3, 4, 3, 2, 2]) == 1
  smallestChange([1, 2, 3, 2, 1]) == 0
  */
const smallestChange = (arr) => {

  var ans = 0;
  for (let i = 0; i < Math.floor(arr.length / 2); i++)
    if (arr[i] != arr.at(-i - 1))
      ans++;
  return ans;
}

const testSmallestChange = () => {
  console.assert(smallestChange([1, 2, 3, 5, 4, 7, 9, 6]) === 4)
  console.assert(smallestChange([1, 2, 3, 4, 3, 2, 2]) === 1)
  console.assert(smallestChange([1, 4, 2]) === 1)
  console.assert(smallestChange([1, 4, 4, 2]) === 1)
  console.assert(smallestChange([1, 2, 3, 2, 1]) === 0)
  console.assert(smallestChange([3, 1, 1, 3]) === 0)
  console.assert(smallestChange([1]) === 0)
  console.assert(smallestChange([0, 1]) === 1)
}

testSmallestChange()

const testSmallestChange = () => {
  console.assert(smallestChange([1, 2, 3, 5, 4, 7, 9, 6]) === 4)
  console.assert(smallestChange([1, 2, 3, 4, 3, 2, 2]) === 1)
  console.assert(smallestChange([1, 2, 3, 2, 1]) === 0)
  console.assert(smallestChange([3, 1, 1, 3]) === 0)
}
testSmallestChange()


Prompt:
/*
  Write a function that accepts two lists of strings and returns the list that has
  total number of chars in the all strings of the list less than the other list.

  if the two lists have the same number of chars, return the first list.

  Examples
  totalMatch([], []) ➞ []
  totalMatch(['hi', 'admin'], ['hI', 'Hi']) ➞ ['hI', 'Hi']
  totalMatch(['hi', 'admin'], ['hi', 'hi', 'admin', 'project']) ➞ ['hi', 'admin']
  totalMatch(['hi', 'admin'], ['hI', 'hi', 'hi']) ➞ ['hI', 'hi', 'hi']
  totalMatch(['4'], ['1', '2', '3', '4', '5']) ➞ ['4']
  */
const totalMatch = (lst1, lst2) => {

  var l1 = lst1.reduce(((prev, item) => prev + item.length), 0);
  var l2 = lst2.reduce(((prev, item) => prev + item.length), 0);
  if (l1 <= l2)
    return lst1;
  else
    return lst2;
}

const testTotalMatch = () => {
  console.assert(JSON.stringify(totalMatch([], [])) === JSON.stringify([]))
  console.assert(
    JSON.stringify(totalMatch(['hi', 'admin'], ['hi', 'hi'])) ===
      JSON.stringify(['hi', 'hi'])
  )
  console.assert(
    JSON.stringify(
      totalMatch(['hi', 'admin'], ['hi', 'hi', 'admin', 'project'])
    ) === JSON.stringify(['hi', 'admin'])
  )
  console.assert(
    JSON.stringify(totalMatch(['4'], ['1', '2', '3', '4', '5'])) ===
      JSON.stringify(['4'])
  )
  console.assert(
    JSON.stringify(totalMatch(['hi', 'admin'], ['hI', 'Hi'])) ===
      JSON.stringify(['hI', 'Hi'])
  )
  console.assert(
    JSON.stringify(totalMatch(['hi', 'admin'], ['hI', 'hi', 'hi'])) ===
      JSON.stringify(['hI', 'hi', 'hi'])
  )
  console.assert(
    JSON.stringify(totalMatch(['hi', 'admin'], ['hI', 'hi', 'hii'])) ===
      JSON.stringify(['hi', 'admin'])
  )
  console.assert(
    JSON.stringify(totalMatch([], ['this'])) === JSON.stringify([])
  )
  console.assert(
    JSON.stringify(totalMatch(['this'], [])) === JSON.stringify([])
  )
}

testTotalMatch()

const testTotalMatch = () => {
  console.assert(JSON.stringify(totalMatch([], [])) === JSON.stringify([]))
  console.assert(
    JSON.stringify(
      totalMatch(['hi', 'admin'], ['hi', 'hi', 'admin', 'project'])
    ) === JSON.stringify(['hi', 'admin'])
  )
  console.assert(
    JSON.stringify(totalMatch(['4'], ['1', '2', '3', '4', '5'])) ===
      JSON.stringify(['4'])
  )
  console.assert(
    JSON.stringify(totalMatch(['hi', 'admin'], ['hI', 'Hi'])) ===
      JSON.stringify(['hI', 'Hi'])
  )
  console.assert(
    JSON.stringify(totalMatch(['hi', 'admin'], ['hI', 'hi', 'hi'])) ===
      JSON.stringify(['hI', 'hi', 'hi'])
  )
}
testTotalMatch()


Prompt:
/*Write a function that returns true if the given number is the multiplication of 3 prime numbers
  and false otherwise.
  Knowing that (a) is less then 100.
  Example:
  isMultiplyPrime(30) == true
  30 = 2 * 3 * 5
  */
const isMultiplyPrime = (a) => {

  var isPrime = function (n) {
    for (let j = 2; j < n; j++)
      if (n % j == 0)
        return false;
    return true;
  }

  for (let i = 2; i < 101; i++) {
    if (!isPrime(i)) continue;
    for (let j = 2; j < 101; j++) {
      if (!isPrime(j)) continue;
      for (let k = 2; k < 101; k++) {
        if (!isPrime(k)) continue;
        if (i*j*k == a)
          return true;
      }
    }
  }
  return false;
}

const testIsMultiplyPrime = () => {
  console.assert(isMultiplyPrime(5) === false)
  console.assert(isMultiplyPrime(30) === true)
  console.assert(isMultiplyPrime(8) === true)
  console.assert(isMultiplyPrime(10) === false)
  console.assert(isMultiplyPrime(125) === true)
  console.assert(isMultiplyPrime(3 * 5 * 7) === true)
  console.assert(isMultiplyPrime(3 * 6 * 7) === false)
  console.assert(isMultiplyPrime(9 * 9 * 9) === false)
  console.assert(isMultiplyPrime(11 * 9 * 9) === false)
  console.assert(isMultiplyPrime(11 * 13 * 7) === true)
}

testIsMultiplyPrime()

const testIsMultiplyPrime = () => {
  console.assert(isMultiplyPrime(30) === true)
}
testIsMultiplyPrime()


Prompt:
/*Your task is to write a function that returns true if a number x is a simple
  power of n and false in other cases.
  x is a simple power of n if n**int=x
  For example:
  isSimplePower(1, 4) => true
  isSimplePower(2, 2) => true
  isSimplePower(8, 2) => true
  isSimplePower(3, 2) => false
  isSimplePower(3, 1) => false
  isSimplePower(5, 3) => false
  */
const isSimplePower = (x, n) => {

  if (n == 1)
    return (x == 1);
  var power = 1;
  while (power < x)
    power = power * n;
  return (power == x);
}

const testIsSimplePower = () => {
  console.assert(isSimplePower(1, 4) === true)
  console.assert(isSimplePower(2, 2) === true)
  console.assert(isSimplePower(8, 2) === true)
  console.assert(isSimplePower(3, 2) === false)
  console.assert(isSimplePower(3, 1) === false)
  console.assert(isSimplePower(5, 3) === false)
  console.assert(isSimplePower(16, 2) === true)
  console.assert(isSimplePower(143214, 16) === false)
  console.assert(isSimplePower(4, 2) === true)
  console.assert(isSimplePower(9, 3) === true)
  console.assert(isSimplePower(16, 4) === true)
  console.assert(isSimplePower(24, 2) === false)
  console.assert(isSimplePower(128, 4) === false)
  console.assert(isSimplePower(12, 6) === false)
  console.assert(isSimplePower(1, 1) === true)
  console.assert(isSimplePower(1, 12) === true)
}

testIsSimplePower()

const testIsSimplePower = () => {
  console.assert(isSimplePower(1, 4) === true)
  console.assert(isSimplePower(2, 2) === true)
  console.assert(isSimplePower(8, 2) === true)
  console.assert(isSimplePower(3, 2) === false)
  console.assert(isSimplePower(3, 1) === false)
  console.assert(isSimplePower(5, 3) === false)
}
testIsSimplePower()


Prompt:
/*
  Write a function that takes an integer a and returns true
  if this ingeger is a cube of some integer number.
  Note: you may assume the input is always valid.
  Examples:
  iscube(1) ==> true
  iscube(2) ==> false
  iscube(-1) ==> true
  iscube(64) ==> true
  iscube(0) ==> true
  iscube(180) ==> false
  */
const iscube = (a) => {

  a = Math.abs(a);
  return (Math.pow(Math.round(Math.pow(a, 1.0 / 3.0)), 3) == a);
}

const testIscube = () => {
  console.assert(true === iscube(1))
  console.assert(false === iscube(2))
  console.assert(true === iscube(-1))
  console.assert(true === iscube(64))
  console.assert(false === iscube(180))
  console.assert(true === iscube(1000))
  console.assert(true === iscube(0))
  console.assert(false === iscube(1729))
}

testIscube()

const testIscube = () => {
  console.assert(true === iscube(1))
  console.assert(false === iscube(2))
  console.assert(true === iscube(-1))
  console.assert(true === iscube(64))
  console.assert(false === iscube(180))
  console.assert(true === iscube(0))
}
testIscube()


Prompt:
/*You have been tasked to write a function that receives
  a hexadecimal number as a string and counts the number of hexadecimal
  digits that are primes (prime number=== or a prime=== is a natural number
  greater than 1 that is not a product of two smaller natural numbers).
  Hexadecimal digits are 0=== 1=== 2=== 3=== 4=== 5=== 6=== 7=== 8=== 9=== A=== B=== C=== D=== E=== F.
  Prime numbers are 2=== 3=== 5=== 7=== 11=== 13=== 17===...
  So you have to determine a number of the following digits: 2=== 3=== 5=== 7===
  B (=decimal 11)=== D (=decimal 13).
  Note: you may assume the input is always correct or empty string===
  and symbols A===B===C===D===E===F are always uppercase.
  Examples:
  For num = "AB" the output should be 1.
  For num = "1077E" the output should be 2.
  For num = "ABED1A33" the output should be 4.
  For num = "123456789ABCDEF0" the output should be 6.
  For num = "2020" the output should be 2.
  */
const hexKey = (num) => {

  var primes = "2357BD",
      total = 0;
  for (let i = 0; i < num.length; i++)
    if (primes.includes(num[i]))
      total++;
  return total;
}

const testHexKey = () => {
  console.assert(1 === hexKey('AB'))
  console.assert(2 === hexKey('1077E'))
  console.assert(4 === hexKey('ABED1A33'))
  console.assert(2 === hexKey('2020'))
  console.assert(6 === hexKey('123456789ABCDEF0'))
  console.assert(12 === hexKey('112233445566778899AABBCCDDEEFF00'))
  console.assert(0 === hexKey(''))
}

testHexKey()

const testHexKey = () => {
  console.assert(1 === hexKey('AB'))
  console.assert(2 === hexKey('1077E'))
  console.assert(4 === hexKey('ABED1A33'))
  console.assert(2 === hexKey('2020'))
  console.assert(6 === hexKey('123456789ABCDEF0'))
}
testHexKey()


Prompt:
/*You will be given a number in decimal form and your task is to convert it to
  binary format. The function should return a string, with each character representing a binary
  number. Each character in the string will be '0' or '1'.

  There will be an extra couple of characters 'db' at the beginning and at the end of the string.
  The extra characters are there to help with the format.

  Examples:
  decimalToBinary(15)   # returns "db1111db"
  decimalToBinary(32)   # returns "db100000db"
  */
const decimalToBinary = (decimal) => {

  return "db" + decimal.toString(2) + "db";
}

const testDecimalToBinary = () => {
  console.assert(decimalToBinary(0) === 'db0db')
  console.assert(decimalToBinary(32) === 'db100000db')
  console.assert(decimalToBinary(103) === 'db1100111db')
  console.assert(decimalToBinary(15) === 'db1111db')
}

testDecimalToBinary()

const testDecimalToBinary = () => {
  console.assert(decimalToBinary(32) === 'db100000db')
  console.assert(decimalToBinary(15) === 'db1111db')
}
testDecimalToBinary()


Prompt:
/*You are given a string s.
  Your task is to check if the string is happy or not.
  A string is happy if its length is at least 3 and every 3 consecutive letters are distinct
  For example:
  isHappy(a) => false
  isHappy(aa) => false
  isHappy(abcd) => true
  isHappy(aabb) => false
  isHappy(adb) => true
  isHappy(xyy) => false
  */
const isHappy = (s) => {

  if (s.length < 3)
    return false;
  for (let i = 0; i < s.length - 2; i++)
    if (s[i] == s[i+1] || s[i+1] == s[i+2] || s[i] == s[i+2])
      return false;
  return true;
}

const testIsHappy = () => {
  console.assert(isHappy('a') === false)
  console.assert(isHappy('aa') === false)
  console.assert(isHappy('abcd') === true)
  console.assert(isHappy('aabb') === false)
  console.assert(isHappy('adb') === true)
  console.assert(isHappy('xyy') === false)
  console.assert(isHappy('iopaxpoi') === true)
  console.assert(isHappy('iopaxioi') === false)
}

testIsHappy()

const testIsHappy = () => {
  console.assert(isHappy('a') === false)
  console.assert(isHappy('aa') === false)
  console.assert(isHappy('abcd') === true)
  console.assert(isHappy('aabb') === false)
  console.assert(isHappy('adb') === true)
  console.assert(isHappy('xyy') === false)
}
testIsHappy()


Prompt:
/*It is the last week of the semester and the teacher has to give the grades
  to students. The teacher has been making her own algorithm for grading.
  The only problem is, she has lost the code she used for grading.
  She has given you a list of GPAs for some students and you have to write
  a function that can output a list of letter grades using the following table:
           GPA       |    Letter grade
            4.0                A+
          > 3.7                A
          > 3.3                A-
          > 3.0                B+
          > 2.7                B
          > 2.3                B-
          > 2.0                C+
          > 1.7                C
          > 1.3                C-
          > 1.0                D+
          > 0.7                D
          > 0.0                D-
            0.0                E

  Example:
  numericalLetterGrade([4.0, 3, 1.7, 2, 3.5]) ==> ['A+', 'B', 'C-', 'C', 'A-']
  */
const numericalLetterGrade = (grades) => {

  let letter_grade = []
  for (let i = 0, len = grades.length; i < len; i++) {
    let gpa = grades[i]
    if (gpa == 4.0) {
      letter_grade.push('A+')
    } else if (gpa > 3.7) {
      letter_grade.push('A')
    } else if (gpa > 3.3) {
      letter_grade.push('A-')
    } else if (gpa > 3.0) {
      letter_grade.push('B+')
    } else if (gpa > 2.7) {
      letter_grade.push('B')
    } else if (gpa > 2.3) {
      letter_grade.push('B-')
    } else if (gpa > 2.0) {
      letter_grade.push('C+')
    } else if (gpa > 1.7) {
      letter_grade.push('C')
    } else if (gpa > 1.3) {
      letter_grade.push('C-')
    } else if (gpa > 1.0) {
      letter_grade.push('D+')
    } else if (gpa > 0.7) {
      letter_grade.push('D')
    } else if (gpa > 0.0) {
      letter_grade.push('D-')
    } else {
      letter_grade.push('E')
    }
  }
  return letter_grade
}

const testNumericalLetterGrade = () => {
  console.assert(
    JSON.stringify(numericalLetterGrade([4.0, 3, 1.7, 2, 3.5])) ===
    JSON.stringify(['A+', 'B', 'C-', 'C', 'A-'])
  )
  console.assert(
    JSON.stringify(numericalLetterGrade([1.2])) === JSON.stringify(['D+'])
  )
  console.assert(
    JSON.stringify(numericalLetterGrade([0.5])) === JSON.stringify(['D-'])
  )
  console.assert(
    JSON.stringify(numericalLetterGrade([0.0])) === JSON.stringify(['E'])
  )
  console.assert(
    JSON.stringify(numericalLetterGrade([1, 0.3, 1.5, 2.8, 3.3])) ===
    JSON.stringify(['D', 'D-', 'C-', 'B', 'B+'])
  )
  console.assert(
    JSON.stringify(numericalLetterGrade([0, 0.7])) ===
    JSON.stringify(['E', 'D-'])
  )
}

testNumericalLetterGrade()

const testNumericalLetterGrade = () => {
  console.assert(
    JSON.stringify(numericalLetterGrade([4.0, 3, 1.7, 2, 3.5])) ===
    JSON.stringify(['A+', 'B', 'C-', 'C', 'A-'])
  )
}
testNumericalLetterGrade()


Prompt:
/*Write a function that takes a string and returns true if the string
  length is a prime number or false otherwise
  Examples
  primeLength('Hello') == true
  primeLength('abcdcba') == true
  primeLength('kittens') == true
  primeLength('orange') == false
  */
const primeLength = (string) => {

  let len = string.length
  if (len == 1 || len == 0) { return false }
  for (let i = 2; i * i <= len; i++) {
    if (len % i == 0) { return false }
  }
  return true
}

const testPrimeLength = () => {
  console.assert(primeLength('Hello') === true)
  console.assert(primeLength('abcdcba') === true)
  console.assert(primeLength('kittens') === true)
  console.assert(primeLength('orange') === false)
  console.assert(primeLength('wow') === true)
  console.assert(primeLength('world') === true)
  console.assert(primeLength('MadaM') === true)
  console.assert(primeLength('Wow') === true)
  console.assert(primeLength('') === false)
  console.assert(primeLength('HI') === true)
  console.assert(primeLength('go') === true)
  console.assert(primeLength('gogo') === false)
  console.assert(primeLength('aaaaaaaaaaaaaaa') === false)
  console.assert(primeLength('Madam') === true)
  console.assert(primeLength('M') === false)
  console.assert(primeLength('0') === false)
}

testPrimeLength()

const testPrimeLength = () => {
  console.assert(primeLength('Hello') === true)
  console.assert(primeLength('abcdcba') === true)
  console.assert(primeLength('kittens') === true)
  console.assert(primeLength('orange') === false)
}
testPrimeLength()


Prompt:
/*
  Given a positive integer n, return the count of the numbers of n-digit
  positive integers that start or end with 1.
  */
const startsOneEnds = (n) => {

  if (n == 1) { return 1 }
  let t = 18
  for (let i = 2; i < n; i++) {
    t = t * 10
  }
  return t
}

const testStartsOneEnds = () => {
  console.assert(startsOneEnds(1) === 1)
  console.assert(startsOneEnds(2) === 18)
  console.assert(startsOneEnds(3) === 180)
  console.assert(startsOneEnds(4) === 1800)
  console.assert(startsOneEnds(5) === 18000)
}

testStartsOneEnds()


Prompt:
/*Given a positive integer N, return the total sum of its digits in binary.

  Example
      For N = 1000, the sum of digits will be 1 the output should be "1".
      For N = 150, the sum of digits will be 6 the output should be "110".
      For N = 147, the sum of digits will be 12 the output should be "1100".

  Variables:
      @N integer
           Constraints: 0 ≤ N ≤ 10000.
  Output:
       a string of binary number
  */
const solve = (N) => {

  let t = 0
  while (N > 0) {
    t += N % 10
    N = (N - N % 10) / 10
  }
  return t.toString(2)
}

const testSolve = () => {
  console.assert(solve(1000) === '1')
  console.assert(solve(150) === '110')
  console.assert(solve(147) === '1100')
  console.assert(solve(333) === '1001')
  console.assert(solve(963) === '10010')
}

testSolve()


Prompt:
/*Given a non-empty list of integers lst. add the even elements that are at odd indices..

  Examples:
      add([4, 2, 6, 7]) ==> 2
  */
const add = (lst) => {

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

const testAdd = () => {
  console.assert(add([4, 2, 6, 7]) === 2)
}
testAdd()