/ Gists / Composable: RecipeCalculator (dynamic method call)
On gists

Composable: RecipeCalculator (dynamic method call)

Vue.js

useRecipeCalculator.js Raw #

/* eslint-disable no-unused-vars */
import { ref, readonly } from 'vue'

const stepsMax = {
  parts: 16,
  weight: 7
}
const selected = {
  type: null,
  amount: null
}

const amount = ref(0)
let step = 0

const calcMethods = {
  increaseWeight: () => {
    if (step >= stepsMax[selected.type]) {
      return
    }
    amount.value *= 2
    step++
  },
  decreaseWeight: () => {
    if (amount.value <= selected.amount) {
      return
    }
    amount.value /= 2
    step--
  },
  increaseParts: () => {
    if (step >= stepsMax[selected.type]) {
      return
    }
    amount.value++
    step++
  },
  decreaseParts: () => {
    if (amount.value <= 1) {
      return
    }
    amount.value--
    step--
  }
}

const increase = () => {
  const fn = `increase${selected.type.charAt(0).toUpperCase() + selected.type.slice(1)}`
  calcMethods[fn]()
}

const decrease = () => {
  const fn = `decrease${selected.type.charAt(0).toUpperCase() + selected.type.slice(1)}`
  calcMethods[fn]()
}

/**
 * @param {string} type - The type of ratio, must be 'parts' or 'weight'.
 * @param {number} recipeAmount - The amount of ratio.
 * @returns {{ amount: Readonly<number>, increase: () => void, decrease: () => void }}
 */
export const useRecipeCalculator = (type, recipeAmount) => {
  selected.type = type
  selected.amount = recipeAmount
  amount.value = recipeAmount

  return {
    amount: readonly(amount),
    increase,
    decrease
  }
}