英文:
How to use previous value of derived store to compute min max values in svelte
问题
以下是已翻译的代码部分:
let base_values = writable({ x: 0, y: 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(a, previous_b);
let max_b = Math.max(a, previous_b);
// 我知道这些 previous_a previous_b 等等在任何地方都没有被声明
// 我只是想展示我想要的东西。
return {
a,
b,
min_a,
min_b,
max_a,
max_b,
}
});
希望这有所帮助。
英文:
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.
答案1
得分: 0
变量可以在派生存储之外声明,并在回调结束时进行更新。
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,
}
});
英文:
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,
}
});
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论