4 Exercises - kylebot0/functional-programming GitHub Wiki

Exercises i've done

The first exercise i've done is a data cleaning exercise. The goal was to clean a complete string of data to something usefull, like an array or a json object. I've decided to clean up some color hexcodes.

This was the string i tried to clean up:

let dataString = `Kleur haar (HEX code)
#915B05
#955f20
#3D2314
#cb9a49
#513723
#B0780D
#EBDBC7
a88473
#2e0707

#3C2B1C
faf0be
1a1b16
#5F5D43
#faf0be
cecb9f
#AF9239
#8B4513
#ffd700

#79553d
#45322e
ffc108
FAF0BE
Bruin
`

This is only a small part of the string. But as you can see there is a lot of wrong data in here. Some things i came across:

  1. 6 numbers / letters without the #
  2. Normal words
  3. More than 1 hexcode in a line
  4. lowercase
let stringArray = dataString.split("\n");
let newStringArray = [];

With this tiny bit of code i decide to split the original string to an array with where it ends at a newline. Then i decided to make a new array, to put everything in to not overwrite the original array. This isn't quite a pure function

function parseStringsInArrayToHexcode(stringArray) {
  //Eerste entry verwijderen
  stringArray.shift();
  for (let hexCode of stringArray) {
    hexCode = hexCode.toUpperCase();
    if (checkHexcodeMatch(hexCode)) {
      pushToNewArray(hexCode);
    } else if (hexCode.length < 6 || hexCode.length > 7) {
      console.log(hexCode.length);
      hexCode = null;
      pushToNewArray(hexCode);
    } else if (hexCode.length == 6) {
      hexCode = "#" + hexCode;
      pushToNewArray(hexCode);
    }
  }
  return newStringArray;
}

This piece of code loops over the entire array and assigns the value hexCode to the value of the index.

 for (let hexCode of stringArray) {

As we had to to apply functional programming to the code, i did some refactoring and got some external function to make the code cleaner and more reusable. With the for of loop i loop over the entire array and check if it has certain values, and if it contains that value i change it. When changed i need to save it to the new array. I do that with the function pushToNewArray(hexCode).

function pushToNewArray(hexCode) {
  return newStringArray.push(hexCode);
}

It's a basic function that just returns a push with the hexcode. In the previous code i also check if a hexcode matches with an actual hexcode i do that with a checkHexcodeMatch(hexCode) function.

function checkHexcodeMatch(hexCode) {
  if (hexCode.match(/^#([0-9a-f]{3}|[0-9a-f]{6})$/i)) {
    return true;
  } else {
    return false;
  }
}

This tries to check if a hexcode contains all of the correct characters, if it does it just returns true, and pushes it to the new array without manipulation. And thats all of the code, all you need to do is just call the function and give an array of hexcodes to the function as a parameter.