Skip to content

Commit

Permalink
feat: add new utility useEntityValueEqualsForMinimumDuration
Browse files Browse the repository at this point in the history
  • Loading branch information
TheNoim committed Jan 24, 2023
1 parent 5821362 commit 47617c4
Showing 1 changed file with 30 additions and 3 deletions.
33 changes: 30 additions & 3 deletions reactive_home/src/composeables/useStateForDuration.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
import { useState } from "./useState.ts";
import type { FullfilledUseState } from "./useState.ts";
import { subSeconds } from "../dep.ts";
import { useNow } from "../dep.ts";
import { computed } from "../dep.ts";
import { computed, unref, useNow, subSeconds } from "../dep.ts";
import type { UseNewBooleanEntity } from "./useNewBoolean.ts";
import type { UseNewLightEntity } from "./useNewLight.ts";
import type { MaybeRef } from "../lib/types.ts";

export function useStateForDuration(
entity: string,
Expand Down Expand Up @@ -41,3 +42,29 @@ export function useNewStateForDuration(
);
});
}

/**
* Checks if an entity value is equals a given state for a minimum amount of seconds.
* @param entity Entity which state should be checked
* @param equalsState State to be equal. Can be reactive
* @param forDuration Duration in seconds
* @param clockSourceInterval How often it should get checked in ms.
* @returns Reactive boolean
*/
export function useEntityValueEqualsForMinimumDuration<
Input extends UseNewBooleanEntity | UseNewLightEntity
>(
entity: Input,
equalsState: MaybeRef<Input["value"]>,
forDuration: number,
clockSourceInterval = 1000
) {
const now = useNow({ interval: clockSourceInterval });

return computed(() => {
return (
entity.value === unref(equalsState) &&
entity.lastChanged < subSeconds(now.value, forDuration)
);
});
}

0 comments on commit 47617c4

Please sign in to comment.