DEV Community

Discussion on: What's one of the ugliest piece of code you've written so far?

Collapse
 
deciduously profile image
Ben Lovy

I think this snippet of ReasonML is pretty horrible, from my very first larger functional programming project:

let add_extended_room = (school, classroom) => {
  let target = ref(school.classrooms);

  if (Array.length(target^) == 0) {
    target := Array.append(target^, Array.make(1, classroom));
  } else {
    let already_included =
      Array.map((oldr: classroom) => oldr.letter, school.classrooms);
    let found = ref(false);
    let idx = ref(0) /* This will only be read later if found is toggled to true*/;
    Array.iteri(
      (i, l) =>
        if (classroom.letter == l) {
          found := true;
          idx := i;
        },
      already_included,
    );
    if (found^) {
      /* We've already seen this letter - mash the new kid list into the matching existing kid list */
      let old_classroom = school.classrooms[idx^];
      let new_classroom = {
        ...old_classroom,
        capacity:
          get_extended_capacity(classroom.letter, school.extended_day_config)
          |> int_of_string,
        kids: ref(Array.append(old_classroom.kids^, classroom.kids^)),
      };
      target^[idx^] = new_classroom;
    } else {
      /* This is a new extended day room - add it as-is, grabbing the extended day capacity */
      target :=
        Array.append(
          target^,
          Array.make(
            1,
            {
              ...classroom,
              capacity:
                get_extended_capacity(
                  classroom.letter,
                  school.extended_day_config,
                )
                |> int_of_string,
            },
          ),
        );
    };
  };

  {...school, classrooms: target^};
};

let get_extended_rooms = school => {
  /* Returns a `school` of the extended kids */
  let s = get_extended_kids(school);
  Array.fold_left(
    add_extended_room,
    {...school, classrooms: [||]},
    s.classrooms,
  );
};

It takes a list of classrooms, each containing a letter and a list of kids, and returns a subset of them, using rules from separate list of classrooms and parameters for transforming the data. It's a bit of a complicated operation by nature, but it could have been broken down or broken out into sub-steps. Writing one massive convoluted fold is not the way to go.

This technically works, but I'm seriously glad I never had to make any sort of change to it, and I can only tell you what it does now because I remember the problem, not because looking at this code means anything to me.