Skip to content

Commit

Permalink
fix: extract common function for set operations
Browse files Browse the repository at this point in the history
  • Loading branch information
maxiaokai1996 committed Oct 23, 2024
1 parent c7bb04c commit ed3eda8
Showing 1 changed file with 10 additions and 8 deletions.
18 changes: 10 additions & 8 deletions packages/hooks/src/useSet/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,25 +5,27 @@ function useSet<K>(initialValue?: Iterable<K>) {
const getInitValue = () => new Set(initialValue);
const [set, setSet] = useState<Set<K>>(getInitValue);

const updateSet = (updater: (set: Set<K>) => Set<K>) => {
setSet((prevSet) => updater(new Set(prevSet)));
};

const add = (key: K) => {
if (set.has(key)) {
return;
}
setSet((prevSet) => {
const temp = new Set(prevSet);
temp.add(key);
return temp;
updateSet((newSet) => {
newSet.add(key);
return newSet;
});
};

const remove = (key: K) => {
if (!set.has(key)) {
return;
}
setSet((prevSet) => {
const temp = new Set(prevSet);
temp.delete(key);
return temp;
updateSet((newSet) => {
newSet.delete(key);
return newSet;
});
};

Expand Down

0 comments on commit ed3eda8

Please sign in to comment.