Search code examples
javascriptreactive-programmingsveltestore

How to use previous value of derived store to compute min max values in svelte


I have one writeble svelte store and one derived svelte store setup like this.

let base_values = writable({ x: 0, y: 0 });
let generated_values = derived(base_values, (changed_values) => {
  // generating some values from the base store
  // these functions could be anything. This is just an example
  let a = Math.sin(changed_values.x);
  let b = Math.cos(changed_values.y); 
  // this is where the trouble starts
  let min_a = Math.min(a, previous_a);
  let max_a = Math.max(a, previous_a);
  let min_b = Math.min(a, previous_b);
  let max_b = Math.max(a, previous_b);
  // I know these previous_a previous_b etc are not declared anywhere
  // I am just trying to show what I want there.
  return {
    a,
    b,
    min_a,
    min_b,
    max_a,
    max_b,
  }
});

I have reread the svelte stores documentation multiple times trying to find a way to get access to a derived stores previous value and have not been successful. Is there a way to do this?

Edit: Fixed variable names.


Solution

  • The variables could be declared outside the derived store and updated at the end of the callback

        let base_values = writable({ x: 0, y: 0 });
    
        let previous_a = 0 //Math.sin(0)
        let previous_b = 1 //Math.cos(0)
    
        let generated_values = derived(base_values, (changed_values) => {
    
            let a = Math.sin(changed_values.x);
            let b = Math.cos(changed_values.y); 
    
            let min_a = Math.min(a, previous_a);
            let max_a = Math.max(a, previous_a);
            let min_b = Math.min(b, previous_b);
            let max_b = Math.max(b, previous_b);
    
            previous_a = a
            previous_b = b
    
            return {
                a,
                b,
                min_a,
                min_b,
                max_a,
                max_b,
            }
        });