简体   繁体   中英

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);
    }
  };
}

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM