webfansplz / vuejs-challenges

Collection of Vue.js challenges
https://vuejs-challenges.netlify.app/
MIT License
2.71k stars 188 forks source link

17 - 计数器 #2078

Open gracelinmumu opened 1 year ago

gracelinmumu commented 1 year ago
// 你的答案
function useCounter(initialValue = 0, options: UseCounterOptions = {}) {
  const count = ref(initialValue);
  const min = options.hasOwnProperty('min') ? options.min : -Infinity;
  const max = options.hasOwnProperty('max') ? options.max : -Infinity;

  const getCount = (newValue: number) => {
    return Math.max(Math.min(max, newValue), min);
  }

  const inc = () => {
    count.value = getCount(count.value + 1);
  }

  const dec = () => {
    count.value = getCount(count.value - 1);
  }

  const reset = () => {
    count.value = initialValue;
  }

  return {
    inc,
    dec,
    count,
    reset,
  }
}
LouisFonda commented 4 months ago

const min = options.hasOwnProperty('min') ? options.min : -Infinity; - const max = options.hasOwnProperty('max') ? options.max : -Infinity; + const max = options.hasOwnProperty('max') ? options.max : Infinity;