Functions

All code revolves around functions and procedures. In this area, we will work a lot with functions, treat them like first class objects since most programming languages use them like that.

Exercise 1 - custom sorting

We need to create a custom sorting algorithm, using the built in sorting of the chosen programming language. You need to investigate to see how you can pass a different comparison to the default sorting.

For this exercise, we need to create a smart_search(my_array), that accepts an array that can have items of different data types. The function needs to return the array, sorted like this: the integers must be before all the strings, and all the boolean after the strings (so integers, strings, booleans). For each type of data, we need to sort them in their natural order (for booleans, let's consider the order false, true as their natural order).

smart_search([1, "test", "hello", true, -2, "world", false])
// [-2, 1, "test", "hello", "world", false, true]

Exercise 2 - algorithm

For this exercise, we have the following algorithm:

result = []
for item in sort(items):
  if condition(item):
    result.append(then(item))
  else:
    result.append(otherwise(item))
return result

We need to implement this highly customizable algorithm to be called like this: algorithm(my_array, sort_func, condition_func, then_func, otherwise_func) (one array and 4 functions passed as parameters).

Example

algorithm([4, 3, 2, 1], arr => { arr.sort(); return arr }, el => el % 2 == 0, el => el * 2 , el => el * 3)
// should return [3, 4, 9, 8] - even numbers are doubled, odd numbers are tripled
algorithm([4, 3, 2, 1], sorted, lambda el: el * 2, lambda el: el * 3)
// should return [3, 4, 9, 8] - even numbers are doubled, odd numbers are tripled