Skip to content

Last Changed

Tracking the last time the value changed.

๐ŸŽฌ Usage

<script>
    import {last_changed} from "@sveu/shared"

    const {value, timestamp} = last_changed(7)
</script>

๐Ÿ‘ฉโ€๐Ÿ’ปAPI

๐Ÿ‘ป Arguments

Name Description Type Required
initial_value Initial value MaybeStore<T> Yes
initial_timestamp Initial timestamp number No

โ†ฉ๏ธ Returns

Name Type
value Watchable
timestamp Readable<number>

๐Ÿงช Playground

Source Code ๐Ÿ‘€

Source Code
import { to_readable } from "../to_readable"
import { to_writable } from "../to_writable"
import type { MaybeStore } from "../utils"
import { watchable } from "../watchable"

/**
 * A function that tracks changes to value and update a timestamp.
 *
 * @param initial_value - The initial value of the store.
 *
 * @param initial_timestamp- An optional initial timestamp.
 *
 * @returns An object containing the store and the timestamp store.
 */
export function last_changed<T>(
    initial_value: MaybeStore<T>,
    initial_timestamp?: number
) {
    const timestamp = to_writable(initial_timestamp ?? +Date.now())

    const value = watchable<T>(initial_value, () => timestamp.set(+Date.now()))

    return { value, timestamp: to_readable(timestamp) }
}

Last update: 2023-03-14