Vera Perrone
Vera Perrone

Reputation: 369

What is the best way to convert OOP classes to FP functions?

I have found a GitHub repository full of JavaScript algorithms and data types. The thing is, everything is written in OOP. I myself, prefer a more FP approach using small, reusable functions. What are some best practices to convert classes to smaller consumable functions?

For now, I can come up with the following working example. Is this the way to go?

OOP:

class LinkedListNode {
  constructor(value, next = null) {
    this.value = value;
    this.next = next;
  }

  toString(callback) {
    return callback ? callback(this.value) : `${this.value}`;
  }
}

FP:

function toString(value, callback) {
  return callback ? callback(value) : `${value}`;
}

function Node(value, next = null) {
  return {
    value,
    next,
    toString(callback) {
      return toString(value, callback);
    }
  };
}

Upvotes: 1

Views: 1208

Answers (1)

Walle Cyril
Walle Cyril

Reputation: 3247

In your second example you still have a method attached to each instance, which is not ideal as soon as you want to reuse this method on a compatible interface. Also it does not play well with many FP js libraries.

To make it clear from the outside that it is not a constructor function, make it start lower case and add a prefix like create for example.

Make functions as pure as possible and do not mix code composition logic (compose, curry) with the business logic. (I talk about callback having nothing to do inside toString)

I am adding export to clearly show that at least 2 functions need to be exported.

export { nodeToString, createNode };

function nodeToString(node) {
  return `${node.value}`;
}

function createNode(value, next = null) {
  return {
    value,
    next
  };
}

It would be used like this

import { nodeToString, createNode } from "./x.js";

const node = createNode(`myvalue`);
const string = nodeToString(node);

Upvotes: 3

Related Questions