jeudi 27 janvier 2022

JS - When to apply the module pattern

I have a module "badges.js", where I just have two methods: "increaseBadge" and "resetBadge".

//
// badges.js
//
function increaseBadge(badgeType, userId, value) {}

function resetBadge(badgeType, userId) {}

module.exports = { increaseBadge, resetBadge };

Does it have sense to apply the module pattern in order to offer a clean interface? Should I use an IIFE or just export an object?

I mean, this

const badges = Object.freeze(
  VALID_BADGES_TYPES.reduce(
    (acc, badgeType) => (
      (acc[badgeType] = {
        increase: (userId, value) =>
          increaseBadge(userId, badgeType, value),

        reset: (userId) =>
          resetBadge(userId, badgeType),
      }),
      acc
    ),
    {}
  )
);

function increaseBadge(badgeType, userId, value) {}

function resetBadge(badgeType, userId) {}

module.exports = badges;

VS encapsulating all the logic with an IIFE (does it have sens? Since I am already declaring all this related stuff in a module)

const badges = (() => {
  function increaseBadge(userId, badgeType, value) {}

  function resetBadge(userId, badgeType) {}

  return Object.freeze(
    VALID_BADGES_TYPES.reduce(
      (acc, badgeType) => (
        (acc[badgeType] = {
          increase: (userId, value) =>
            increaseUserBadge(userId, badgeType, value),

          reset: (userId) => resetUserBadge(userId, badgeType),
        }),
        acc
      ),
      {}
    )
  );
})();

module.exports = badges;

Aucun commentaire:

Enregistrer un commentaire