UNPKG

@coinmeca/ui

Version:

This is a [Next.js](https://nextjs.org/) project bootstrapped with [`create-next-app`](https://github.com/vercel/next.js/tree/canary/packages/create-next-app).

118 lines 3.26 kB
"use client"; import { useState } from "react"; export default function useOrder(initial, mode, fee, available) { const [order, setOrder] = useState({ price: initial?.price || 0, amount: initial?.amount || 0, quantity: initial?.quantity || 0, fees: initial?.fees || 0, total: initial?.total || 0, }); const getAmount = (amount, price) => { const p = price || order?.price; const max = available ? p > 0 && (mode ? available : available * p) : p > 0 && (mode ? amount : amount * p); return max && max < amount ? max : amount; }; const getQuantity = (quantity, price) => { const p = price || order?.price; const max = maxQuantity(p); return max && max < quantity ? max : quantity; }; const maxAmount = () => { return available || order?.amount; }; const maxQuantity = (price) => { const p = price || order?.price; return available && available > 0 && p > 0 ? (mode ? available / p : available * p) : undefined; }; const price = (price) => { if (price === 0) { setOrder({ ...order, price: 0, amount: 0, quantity: 0, fees: 0, total: 0, }); } mode ? amount(order?.amount || 0, price) : quantity(order?.quantity || 0, price); }; const amount = (amount, price) => { let o; const p = price || order?.price; if (amount === 0 || p === 0) { o = { ...order, price: p, amount: 0, quantity: 0, fees: 0, total: 0, }; setOrder(o); return o; } const a = getAmount(amount, p); const q = mode ? a / p : a * p; const f = fees(q); o = { ...order, price: p, amount: a, quantity: q, fees: f, total: q - f, }; setOrder(o); return o; }; const quantity = (quantity, price) => { let o; const p = price || order?.price; if (quantity === 0 || p === 0) { o = { ...order, price: p, amount: 0, quantity: 0, fees: 0, total: 0, }; setOrder(o); return o; } const q = getQuantity(quantity, p); const a = mode ? q * p : q / p; const f = fees(q); o = { ...order, price: p, amount: a, quantity: q, fees: f, total: q - f, }; setOrder(o); return o; }; const reset = (price) => setOrder({ ...order, price: price || order?.price, amount: 0, quantity: 0, fees: 0, total: 0, }); const fees = (quantity) => (quantity === 0 ? 0 : quantity * fee); return { order, price, amount, quantity, reset, maxAmount, maxQuantity }; } //# sourceMappingURL=useOrder.js.map