usestack
Version:
This package allows users to use stacks in React applications as a custom hook.
90 lines (89 loc) • 2.31 kB
JavaScript
// src/index.ts
import { useState } from "react";
function useStack(initialValues = []) {
var _a;
const [stack, setStack] = useState((_a = [...initialValues]) == null ? void 0 : _a.reverse());
const [version, setVersion] = useState(0);
const push = (item) => {
setStack((prev) => {
const newStack = [...prev, item];
return newStack;
});
setVersion((v) => v + 1);
};
const reset = () => {
var _a2;
setStack((_a2 = [...initialValues]) == null ? void 0 : _a2.reverse());
setVersion((v) => v + 1);
};
const shuffle = () => {
setStack((prev) => {
const shuffled = [...prev];
for (let i = shuffled.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[shuffled[i], shuffled[j]] = [shuffled[j], shuffled[i]];
}
return shuffled;
});
setVersion((v) => v + 1);
};
const pop = () => {
let popped;
setStack((prev) => {
const newStack = [...prev];
popped = newStack == null ? void 0 : newStack.pop();
return newStack;
});
setVersion((v) => v + 1);
return popped;
};
const peek = () => {
return stack[(stack == null ? void 0 : stack.length) - 1];
};
const clear = () => {
setStack([]);
setVersion((v) => v + 1);
};
const reverse = () => {
setStack((prev) => {
var _a2;
return (_a2 = [...prev]) == null ? void 0 : _a2.reverse();
});
setVersion((v) => v + 1);
};
const sort = (compareFn) => {
setStack((prev) => {
var _a2, _b;
return (_b = (_a2 = [...prev]) == null ? void 0 : _a2.sort(compareFn)) == null ? void 0 : _b.reverse();
});
setVersion((v) => v + 1);
};
const isEmpty = () => (stack == null ? void 0 : stack.length) === 0;
const size = () => stack == null ? void 0 : stack.length;
const values = () => {
var _a2;
return (_a2 = [...stack]) == null ? void 0 : _a2.reverse();
};
const print = () => {
var _a2, _b;
console.log("[Stack contents top \u2192 bottom]:", (_b = (_a2 = [...stack]) == null ? void 0 : _a2.reverse()) == null ? void 0 : _b.join(", "));
};
return {
push,
pop,
reset,
shuffle,
peek,
clear,
reverse,
sort,
isEmpty,
size,
values,
print,
version
};
}
export {
useStack
};