Skip to content

Instantly share code, notes, and snippets.

@joshnuss
Last active December 21, 2020 17:45
Show Gist options
  • Save joshnuss/a44c58c7adbc79fda9dd61a7478bc217 to your computer and use it in GitHub Desktop.
Save joshnuss/a44c58c7adbc79fda9dd61a7478bc217 to your computer and use it in GitHub Desktop.
Using Svelte derived stores to do compute aggregate values
import {identity} from 'svelte/internal'
import {derived} from 'svelte/store'
// sum multiple stores
export function sum(stores, iterator=identity) {
// define a dervied store
return derived(stores, ($stores, set) => {
// sum the current value of each store
const result = $stores.reduce((acc, n) => acc + iterator(n), 0)
// update this store with the result
set(result)
})
}
// maximum value of multiple stores
export function maximum(stores, iterator=identity) {
// define a dervied store
return derived(stores, ($stores, set) => {
// compute the maximum of all stores
const result = Math.max(...($stores).map(iterator))
// update this store with the result
set(result)
})
}
// minimum value of multiple stores
export function minimum(stores, iterator=identity) {
// define a dervied store
return derived(stores, ($stores, set) => {
// compute the minimum of all stores
const result = Math.min(...($stores).map(iterator))
// update this store with the result
set(result)
})
}
// average values of multiple stores
export function average(stores, iterator=identity) {
return readable(0, set => {
// re-use the `sum` store
const totals = sum(stores, iterator)
// subscribe to changes to `totals`, and compute average
// `totals.subscribe()` returns a callback to unsubscribe
return totals.subscribe(n => set(n / stores.length))
})
}
import { writable } from 'svelte/store'
import { sum, max, min, average } from './aggregateStores.js'
const a = writable(10)
const b = writable(33)
const total = sum([a, b])
const max = maximum([a, b])
const min = minimum([a, b])
const avg = average([a, b])
// can also pass a custom iterator to pick out attributes
const a = writable({value: 10})
const b = writable({value: 33})
const total = sum([a, b], n => n.value)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment