UNPKG

@mcabreradev/filter

Version:

A powerful, SQL-like array filtering library for TypeScript and JavaScript with advanced pattern matching, MongoDB-style operators, deep object comparison, and zero dependencies

49 lines (48 loc) 1.53 kB
import { ref, computed, watch, unref, onUnmounted, getCurrentInstance, onScopeDispose, } from 'vue'; import { filter } from '../../core'; import { DEFAULT_DEBOUNCE_DELAY } from './vue.constants'; import { debounce } from '../shared'; export function useDebouncedFilter(data, expression, options) { const { delay = DEFAULT_DEBOUNCE_DELAY, ...filterOptions } = options || {}; const debouncedExpression = ref(unref(expression)); const isPending = ref(false); const debouncedUpdate = debounce((expr) => { debouncedExpression.value = expr; isPending.value = false; }, delay); watch(() => unref(expression), (newExpression) => { isPending.value = true; debouncedUpdate(newExpression); }, { immediate: false }); if (getCurrentInstance()) { onUnmounted(() => { debouncedUpdate.cancel(); }); } else { onScopeDispose(() => { debouncedUpdate.cancel(); }); } const filtered = computed(() => { const dataValue = unref(data); if (!dataValue || dataValue.length === 0) { return []; } try { return filter(dataValue, debouncedExpression.value, filterOptions); } catch { return []; } }); const isFiltering = computed(() => { const dataValue = unref(data); return filtered.value.length !== dataValue.length; }); return { filtered, isFiltering, isPending, }; }