@darwish/hooks-core
Version:
94 lines (93 loc) • 3.59 kB
JavaScript
var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
if (ar || !(i in from)) {
if (!ar) ar = Array.prototype.slice.call(from, 0, i);
ar[i] = from[i];
}
}
return to.concat(ar || Array.prototype.slice.call(from));
};
import { useMemo, useRef } from "react";
import { isFunction } from "@darwish/utils-is";
import useUpdate from "./useUpdate";
var resolveHooksState = function (newList, oldList) {
if (isFunction(newList)) {
return newList.length ? newList(oldList) : newList([]);
}
return newList;
};
function useList(initialList) {
var list = useRef(resolveHooksState(initialList, []));
var updateFn = useUpdate();
var utils = useMemo(function () {
return {
set: function (newList) {
list.current = resolveHooksState(newList, list.current);
updateFn();
},
push: function (newItem) {
utils.set(__spreadArray(__spreadArray([], list.current, true), [newItem], false));
},
updateAt: function (updateIndex, updateItem) {
utils.set(list.current.map(function (item, i) { return (i === updateIndex ? updateItem : item); }));
},
insertAt: function (insertIndex, insertItem) {
utils.set(function (prev) {
var resArr = [];
prev.forEach(function (item, i) {
if (i === insertIndex) {
resArr.push(insertItem);
}
resArr.push(item);
});
return resArr;
});
},
update: function (predicate, updateItem) {
utils.set(function (prev) {
return prev.map(function (item) { return (predicate(item, updateItem) ? updateItem : item); });
});
},
updateFirst: function (predicate, updateItem) {
var index = list.current.findIndex(function (item) {
return predicate(item, updateItem);
});
if (index >= 0) {
utils.updateAt(1, updateItem);
}
},
upsert: function (predicate, updateItem) {
var index = list.current.findIndex(function (item) {
return predicate(item, updateItem);
});
if (index >= 0) {
utils.updateAt(1, updateItem);
}
else {
utils.push(updateItem);
}
},
sort: function (compareFn) {
utils.set(__spreadArray([], list.current, true).sort(compareFn));
},
filter: function (callbackFn, thisArg) {
utils.set(function (curr) { return curr.slice().filter(callbackFn, thisArg); });
},
removeAt: function (index) {
utils.set(function (prev) {
var arr = prev.slice();
arr.splice(index, 1);
return arr;
});
},
clear: function () {
utils.set([]);
},
reset: function () {
utils.set(initialList);
},
};
}, []);
return [list.current, utils];
}
export default useList;