We are going to build a dynamic config system that supports:
- Percent ramps: values that change over time from a start percentage to an end percentage over a duration.
- Freezes: at specific times (or after a ramp) the value can be frozen for a duration.
We'll design a configuration that can describe multiple stages for a parameter.
Example of a config for a parameter (say, volume):
[
{ "type": "ramp", "start_percent": 0, "end_percent": 100, "duration": 10, "easing": "linear" },
{ "type": "freeze", "duration": 5 }
]
This would mean:
- From time 0 to 10: ramp from 0% to 100% linearly.
- Then freeze at 100% for 5 seconds.
We can also have multiple ramps and freezes.
Alternatively, we can have a more flexible config that allows:
- A series of stages, each stage being either a ramp or a freeze.
- For a ramp, we specify start and end percentages (as numbers between 0 and 100) and duration.
- For a freeze, we specify the duration to hold the last value.
However, note that the first stage must be a ramp because we need an initial value.
But wait, what if we want to start from a specific value? We can set the start_percent of the first ramp.
Alternatively, we can have an initial value and then ramps and freezes. But the above design is simple.
Let's assume the config is an array of stages. The first stage must be a ramp.
How about:
stage1: ramp from A to B in T1
stage2: freeze for T2 (value fixed at B)
stage3: ramp from B to C in T3
stage4: freeze for T4 (value fixed at C)
We can also consider having an initial value (start_percent) in the first ramp.
But note: the ramp stage has start_percent and end_percent. The start_percent of the first ramp is the initial value.
However, what if we want to change the value abruptly (like a jump) without a ramp? We can do a ramp with 0 duration? Or we can have a "set" stage?
Let's stick to ramps and freezes for now. If we need a jump, we can set the start and end to different values with 0 duration? But then it's not a ramp.
Alternatively, we can allow a ramp with duration 0 to mean an immediate change.
Let's define:
Ramp stage:
- type: "ramp"
- start_percent: number (0-100) [optional: if not provided, use the last value? But for the first one we must have it]
- end_percent: number (0-100)
- duration: number (seconds, must be >=0)
- easing: string (optional, default "linear") - we can define easing functions.
Freeze stage:
- type: "freeze"
- duration: number (seconds, must be >=0)
However, for the first ramp, we must specify the start_percent. For subsequent ramps, we can omit the start_percent and use the last value (from the previous stage).
But note: after a freeze, the value is the same as before the freeze. So the next ramp's start_percent would be that value.
So we can design:
For a ramp stage:
If it's the first stage, then start_percent is required.
If it's not the first stage and start_percent is omitted, then we use the value at the end of the previous stage.
For a freeze stage:
It doesn't have a start or end, it just holds the current value.
Let's write an example:
[
{ "type": "ramp", "start_percent": 0, "end_percent": 100, "duration": 10 },
{ "type": "freeze", "duration": 5 },
{ "type": "ramp", "end_percent": 50, "duration": 10 } // start_percent omitted, so starts from 100 (the last value after freeze)
]
This would:
- 0 to 10s: 0 -> 100
- 10 to 15s: freeze at 100
- 15 to 25s: 100 -> 50
Now, about easing: we can support common easing functions (linear, easeIn, easeOut, easeInOut, etc.) or even custom functions.
But for simplicity, let's assume we have a set of named easings. We can define:
"linear": t => t
"easeInQuad": t => tt
"easeOutQuad": t => t(2-t)
"easeInOutQuad": t => t<0.5 ? 2tt : -1+(4-2*t)*t
... and so on.
We can have a map of easing functions.
Now, we need to compute the value at any given time t (from the start of the config).
Steps:
Let current_time = 0.
For each stage in the config:
If stage is a ramp:
Let stage_duration = stage.duration
If t is within [current_time, current_time + stage_duration]:
Let local_t = (t - current_time) / stage_duration (normalized to [0,1])
Apply easing to local_t to get eased_t.
Let start = stage.start_percent if defined, else last_value (from previous stage)
Let end = stage.end_percent
value = start + (end - start) * eased_t
return value
Else:
Update current_time += stage_duration
last_value = stage.end_percent (or if duration 0, then we set last_value to end_percent immediately)
If stage is a freeze:
Let stage_duration = stage.duration
If t is within [current_time, current_time + stage_duration]:
return last_value (which is the value at the start of the freeze)
Else:
current_time += stage_duration
If t is beyond the total time, we can return the last value (or last ramp's end_percent) or maybe error?
But note: after the last stage, we might want to hold the last value? Actually, the config doesn't specify what happens after.
We can decide that after the last stage, the value remains at the last value (if the last stage was a ramp, then the end_percent; if freeze, then the frozen value).
So if t > total_time, we return the last_value.
However, what if the last stage is a ramp and we want to hold at the end? We can add a freeze at the end.
But let's not assume. We'll return the last value for any t beyond the total time.
Implementation:
We'll parse the config and then create a function that takes t (in seconds) and returns the value (0-100).
We'll also need to handle the case where a ramp has duration 0. Then we immediately jump to the end_percent.
Let's code accordingly.
Steps for the function:
let total_time = 0
let current_value = 0 // we don't know until we see the first ramp
Actually, we must have a first ramp with a start_percent. So we can set current_value to that start_percent.
But note: the first stage must be a ramp? We can enforce that.
Alternatively, we can allow a config that starts with a freeze? That doesn't make sense because we don't have an initial value.
So we require the first stage to be a ramp.
Algorithm:
let stages = config
let current_time = 0
let last_value = null
for each stage in stages:
if stage.type == 'ramp':
if last_value === null:
// This is the first ramp
if (stage.start_percent === undefined) {
throw new Error("First ramp must have start_percent")
}
let start = stage.start_percent
else:
let start = (stage.start_percent !== undefined) ? stage.start_percent : last_value
let end = stage.end_percent
let duration = stage.duration
if (duration === 0) {
// Immediate jump
last_value = end
current_time += 0 // no time passes
// but note: if t is exactly at current_time, we are in this stage? Actually, we are in the stage for 0 duration.
// We'll handle it by: if t in [current_time, current_time] then we are in this stage? That's a point.
// We can treat 0 duration as an instantaneous change at current_time.
} else {
if (t >= current_time && t < current_time + duration) {
let local_t = (t - current_time) / duration
let eased_t = easingFunction(stage.easing || 'linear')(local_t)
return start + (end - start) * eased_t
} else if (t >= current_time + duration) {
// We've passed this ramp, set last_value to end
last_value = end
current_time += duration
}
// if t < current_time, we are in a previous stage, so we break? Actually we are iterating in order.
}
if stage.type == 'freeze':
let duration = stage.duration
if (t >= current_time && t < current_time + duration) {
return last_value
} else if (t >= current_time + duration) {
current_time += duration
// last_value remains the same
}
// If we get here, t is beyond all stages.
return last_value
However, note: if we have a ramp with 0 duration, then at the exact current_time we are in that ramp? But the condition for ramp with duration>0 uses [current_time, current_time+duration). For 0 duration, we need to handle separately.
Let's adjust:
For a ramp with duration 0:
It happens at exactly current_time (and for 0 time). So if t == current_time, then we should return the end_percent? But note that at the exact time, we are transitioning from start to end? Actually, it's instantaneous.
We can say: if duration==0, then for t == current_time, we return end_percent? But what about the start? We don't care because it's instantaneous.
However, note that the previous stage (if any) would have set last_value to something. And then at current_time, we jump to end.
So we can handle:
if (duration === 0) {
if (t === current_time) {
last_value = end
return end
} else {
// if t is not exactly current_time, then we skip (because it's instantaneous)
// but then we must update current_time? Actually, we don't add time.
// So we just set last_value to end and then move to next stage? But we are in the loop.
// We can do: if t == current_time, then we are in this stage and return end.
// But if t > current_time, then we have passed this stage (even though it took 0 time) and we set last_value to end and then current_time remains? Actually, we should set current_time to current_time (no change) and then move to next stage.
// This is tricky.
// Alternatively, we can treat 0 duration as a special case that doesn't consume time and sets the value at the current_time.
// Let's change: we don't advance current_time for 0 duration. But then the next stage will start at the same current_time.
// Example:
// ramp from 0 to 100 in 0s at time 0.
// Then freeze for 5s starting at time 0? That would mean at time 0 we are already at 100 and then freeze for 5s.
// But note: the freeze stage starts at current_time (which is 0) and lasts 5s. So at time 0, we are in the freeze? But we just set the value to 100 at time 0.
// We can do:
// For a 0 duration ramp:
// if t == current_time, then we return end.
// and then we set last_value = end (so that the next stage starts with this value)
// and we do not advance current_time.
// Then we move to the next stage. But note: the next stage (freeze) will start at current_time (still 0) and we will be in the freeze for [0,5). But at t=0, we already returned the ramp's value? Actually, we returned the ramp's value at t=0.
// However, the freeze stage would also return the same last_value (which is now 100) for t in [0,5). But we already returned at t=0 from the ramp.
// So we need to break after returning? But we are in a loop.
// Alternatively, we can process the 0 duration ramp by setting last_value and then continuing to the next stage without returning? But then at t=0, we would not return the ramp's value? We would only return when we find a stage that contains t.
// Let's think: we are iterating stages and for each stage we check if t is in the stage's time interval.
// For a 0 duration ramp, the interval is [current_time, current_time] (a point). So if t == current_time, we return the ramp's value (end). But note: the start value of the ramp is only used for the calculation? We don't need it for a 0 duration.
// And then we set last_value to end, and we do not advance current_time.
// Then we move to the next stage. The next stage (freeze) will have interval [current_time, current_time + duration). Since current_time is still 0, and t=0 is in that interval? Actually, the freeze interval is [0,5). So at t=0, we are in both the ramp (point) and the freeze? That's a problem.
// We need to define that the ramp with 0 duration happens at the start of the freeze? Or we can say that the ramp with 0 duration is instantaneous and then we are immediately in the next stage.
// So we should process the 0 duration ramp and then set the value and then move to the next stage without returning? But then at t=0, we wouldn't return the ramp's value? We would only return when we get to the freeze? But the freeze will return the last_value (which is now 100) for t in [0,5). That's correct.
// So we can do:
// For a ramp with duration 0:
// if t == current_time, then we set last_value = end and then continue to the next stage (without returning).
// But note: we are at the exact current_time, and we want the value to be end at that time? Actually, the freeze stage will return the same value for t=0.
// Alternatively, we can treat the 0 duration ramp as not having an interval? It just changes the value at current_time and then we move on.
// So we can do:
// if (stage.type == 'ramp' && stage.duration === 0) {
// if (t === current_time) {
// last_value = stage.end_percent
// }
// // We don't return here, we just update last_value and then continue to next stage.
// // But note: we don't advance current_time.
// }
// However, what if there are multiple 0 duration ramps in a row? We would set last_value multiple times at the same current_time.
// But note: the config is sequential. So if we have:
// ramp (0 duration) from 0 to 100 at time 0
// ramp (0 duration) from 100 to 200 at time 0
// Then at time 0, we would set last_value to 100 and then to 200. So the final value at time 0 would be 200.
// That seems correct.
// But then when we get to the freeze stage (if any) at the same time, we would have the last_value set to 200.
// So we can handle 0 duration ramps without returning, just updating last_value and then moving to the next stage.
// However, what about the condition for the freeze stage? The freeze stage will have an interval [current_time, current_time+duration). If current_time is 0 and we have two 0 duration ramps, then the freeze stage will start at 0 and last for duration. So at t=0, we are in the freeze? But we also processed the 0 duration ramps.
// We are processing the stages in order. So for t=0, we would:
// stage1: ramp 0 duration -> update last_value to 100 (if t==0) and continue.
// stage2: ramp 0 duration -> update last_value to 200 (if t==0) and continue.
// stage3: freeze -> we check if t is in [0,5). Since t=0, we return last_value (200).
// So at t=0, we return 200. That seems correct.
// But note: the first ramp's start_percent? We didn't use it because duration 0. But we required the first ramp to have start_percent? Actually, for a 0 duration ramp, we don't use the start_percent? We only set the value to end_percent.
// However, what if the first ramp is 0 duration and we don't have a start_percent? Then we don't know the initial value? But we are setting the value to end_percent at time 0. So we don't need the start_percent? Actually, we can set the initial value to end_percent at time 0.
// But wait, what if the first stage is a freeze? We said we require the first stage to be a ramp. So we can require that the first stage is a ramp and if it's 0 duration, then we set the initial value to its end_percent.
// So we can adjust:
// For the first ramp (if it's 0 duration), we set last_value to its end_percent at time 0.
// But note: if the first ramp has duration>0, then we use start_percent as the initial value at time 0.
// So we can do:
// let first = true
// for each stage:
// if stage.type == 'ramp':
// let start
// if first:
// if stage.start_percent === undefined:
// throw new Error("First ramp must have start_percent")
// start = stage.start_percent
// first = false
// else:
// start = (stage.start_percent !== undefined) ? stage.start_percent : last_value
// But for 0 duration, we don't use start? Actually, we don't need it because we jump immediately to end.
// However, we must set last_value to end at the current_time (if t==current_time) for 0 duration.
// Let's restructure:
// We'll keep:
// current_time: the start time of the current stage.
// last_value: the value at the start of the current stage (or after the previous stage).
// For a ramp with duration>0:
// We check if t is in [current_time, current_time+duration). If yes, we compute and return.
// If t >= current_time+duration, then we set last_value to end and current_time += duration.
// For a ramp with duration==0:
// This ramp happens at current_time (a point). So if t == current_time, then we set last_value to end (and do not advance current_time).
// But note: we are in the loop and we might have multiple 0 duration ramps at the same current_time.
// For a freeze:
// We check if t is in [current_time, current_time+duration). If yes, return last_value.
// If t >= current_time+duration, then current_time += duration.
// However, note that for a 0 duration ramp, we don't advance current_time. So if we have:
// ramp (0 duration) at time 0 -> set last_value to 100
// freeze for 5s -> interval [0,5)
// Then at t=0, we process the ramp (set last_value to 100) and then we process the freeze (t is in [0,5) so return 100). That's correct.
// But what if the freeze comes first? Then at t=0, we are in the freeze? But we haven't processed the ramp? The order matters.
// The config is an array, so the stages are in order. So we must process in order.
// So for t=0, we first process the ramp (0 duration) and set last_value to 100, then we process the freeze and return 100.
// But note: the freeze stage uses last_value (which is now 100) and returns it for t in [0,5). That's correct.
// Now, what if we have:
// freeze for 5s (starting at 0)
// ramp (0 duration) from 100 to 200 at time 0? But wait, the ramp would be at time 0? But the freeze is from 0 to 5. So the ramp at time 0 would be during the freeze? That doesn't make sense because the freeze is holding the value.
// We must define: the stages are sequential and non-overlapping in time? Actually, they are contiguous.
// The current_time is the start of the current stage. So the first stage starts at 0.
// Then after a stage (ramp or freeze) we set current_time to the end of that stage.
// For a 0 duration ramp, we don't advance current_time, so the next stage starts at the same time.
// But that would mean the next stage starts at the same time? That's overlapping? We don't want that.
// Actually, for a 0 duration ramp, we are changing the value at the current_time and then immediately the next stage starts at the same current_time? That would mean at the same time we are in two stages? That's not good.
// Let's think about the timeline:
// stage1: ramp 0 duration at time 0 -> value becomes 100 at time 0.
// stage2: freeze for 5s -> from time 0 to 5, we freeze at 100.
// But at time 0, we are in the ramp (point) and then in the freeze? Actually, the ramp is instantaneous and then we are in the freeze.
// We can define that a 0 duration ramp does not consume time and sets the value at the current_time, and then we move to the next stage which starts at the same current_time? But then the freeze would start at the same time and we are in the freeze at time 0? That's acceptable because the freeze uses the last_value (which is 100) and returns it for [0,5).
// But note: when we process the freeze stage, we check if t is in [current_time, current_time+duration). Since current_time is 0 and t=0, we are in the freeze.
// So we return the freeze's value (which is 100). That's correct.
// However, what if we have:
// ramp (0 duration) from 0 to 100 at time 0.
// ramp (duration 5) from 100 to 200 starting at time 0? But wait, the second ramp would start at current_time (which is still 0 because the first ramp didn't advance time). Then we have two ramps at the same time? That's not allowed.
// We must advance current_time after a 0 duration ramp? But then we lose the fact that it happened at time 0.
// Alternatively, we can say that a 0 duration ramp is instantaneous and then we set current_time to the same time? That doesn't make sense.
// Let's change the rule: after a 0 duration ramp, we set current_time to current_time (no change) but then we must also consider that the next stage starts at the same time? That would mean the next stage overlaps in time? We don't want that.
// Actually, the stages are meant to be sequential. So after a stage (even 0 duration) we should move to the next stage at the same current_time? That would mean the next stage starts at the same time? Then we have two stages at the same time? That's not sequential.
// We need to define: the stages are in order and each stage starts at the end of the previous stage.
// So if the first stage is 0 duration, it ends at time 0. Then the next stage starts at time 0.
// So we can say: after a 0 duration ramp, we set current_time to current_time (which is the same) but then we are at the end of the ramp and the start of the next stage.
// But then for the next stage, we are at current_time (0) and we are in the next stage? Yes.
// So for the example:
// stage1: ramp 0 duration at time 0 -> ends at time 0.
// stage2: freeze for 5s -> starts at time 0, ends at 5.
// That's correct.
// But what if we have two 0 duration ramps in a row?
// stage1: ramp 0 duration from 0 to 100 -> ends at 0.
// stage2: ramp 0 duration from 100 to 200 -> starts at 0, ends at 0.
// Then both happen at time 0? That's acceptable? We are changing the value twice at the same time? The final value would be 200.
// So we can do:
// For a 0 duration ramp:
// if t == current_time, then set last_value = end.
// Then we set current_time = current_time (no change) and then move to next stage? But we must also consider that the ramp has ended? Actually, we don't need to change current_time because it didn't consume time.
// However, we must be careful: when we process the next stage, we are still at current_time (which is the start of the next stage). So we are at the same time.
// But then for the next stage (which starts at current_time) we might have t == current_time and we would return the value from the next stage? That's what we want.
// So the algorithm for a 0 duration ramp:
// if (t === current_time) {
// last_value = stage.end_percent
// }
// // We do not advance current_time.
// But note: what if the 0 duration ramp is not the first? Then we have a current_time from the previous stage. And if t is exactly that current_time, we set last_value to the ramp's end_percent. Then we continue to the next stage.
// Example:
// freeze for 5s (from 0 to 5)
// ramp (0 duration) from 100 to 200 at time 5.
// At time 5:
// We are in the freeze? Actually, the freeze ends at 5 (since [0,5) doesn't include 5). So at t=5, we are not in the freeze. Then we move to the next stage (ramp) at current_time=5.
// The ramp is 0 duration and t==5, so we set last_value to 200 and then continue? But there is no next stage? Then we return 200.
// That's correct.
// However, what if we have:
// ramp (duration 5) from 0 to 100 (0 to 5)
// freeze for 0 duration at time 5? That doesn't make sense because freeze 0 duration would be instantaneous? But we don't have a freeze 0 duration? We can allow it? Let's not allow freeze 0 duration? Or we can allow it and it would be a no-op? But we can also use a ramp 0 duration to jump.
// We'll allow freeze 0 duration? It would be a stage that doesn't change the value and doesn't consume time? That's the same as nothing? We can disallow.
// Let's disallow freeze with duration 0? Or we can ignore it.
// We'll assume that freeze duration >0.
So let's adjust the code:
We'll have:
for each stage in stages:
if stage.type == 'ramp':
let start
if (last_value === null) {
// first ramp
if (stage.start_percent === undefined) {
throw new Error("First ramp must have start_percent")
}
start = stage.start_percent
} else {
start = (stage.start_percent !== undefined) ? stage.start_percent : last_value
}
let end = stage.end_percent
let duration = stage.duration
if (duration === 0) {
if (t === current_time) {
last_value = end
}
// We don't advance current_time, and we don't return because it's instantaneous.
// But note: if t is not current_time, then we skip? Actually, we are at a specific current_time and if t is not that, then we don't do anything for this stage.
// So we just continue to the next stage.
} else {
if (t >= current_time && t < current_time + duration) {
let local_t = (t - current_time) / duration
let eased_t = easingFunction(stage.easing || 'linear')(local_t)
return start + (end - start) * eased_t
} else if (t >= current_time + duration) {
// We've passed this ramp
last_value = end
current_time += duration
}
// if t < current_time, we are in a previous stage? But we are iterating in order, so t < current_time shouldn't happen because we break when we return?
// Actually, we are checking each stage and if t is in the stage we return. Otherwise we update current_time and last_value and move on.
// But if t < current_time, then we are in a previous stage? That means we missed it? That shouldn't happen because we are iterating from the beginning and current_time is increasing.
// However, if we have a 0 duration ramp and then a ramp with duration>0, then for t exactly at the current_time (which is the start of the 0 duration ramp and then the start of the next ramp) we would not have returned from the 0 duration ramp (because we set last_value but didn't return) and then we check the next ramp? But the next ramp's interval is [current_time, current_time+duration). Since t == current_time, we are in the next ramp? Then we would return the next ramp's value? That's not correct because the 0 duration ramp happened at the same time and changed the value.
// Example:
// stage1: ramp (0 duration) from 0 to 100 at time 0.
// stage2: ramp (duration 5) from 100 to 200 starting at time 0.
// At t=0:
// stage1: duration 0, t==0 -> set last_value=100, but don't return.
// Then stage2: duration 5, t in [0,5) -> we compute and return? But note: the start of stage2 is 100 (because we set last_value to 100) and we are ramping to 200. But at t=0, we should be at 100? Actually, the ramp from 100 to 200 starts at 0 and at t=0 it should be 100.
// So that's correct.
// But what if we have:
// stage1: ramp (0 duration) from 0 to 100 at time 0.
// stage2: ramp (0 duration) from 100 to 200 at time 0.
// stage3: ramp (duration 5) from 200 to 300 starting at time 0.
// At t=0:
// stage1: set last_value=100
// stage2: set last_value=200
// stage3: t in [0,5) -> we compute with start=200, end=300, t=0 -> return 200.
// That's correct.
// So the algorithm works.
}
if stage.type == 'freeze':
let duration = stage.duration
if (duration <= 0) {
// ignore or throw? Let's ignore 0 or negative.
continue
}
if (t >= current_time && t < current_time + duration) {
return last_value
} else if (t >= current_time + duration) {
current_time += duration
}
After the loop, return last_value.
But note: we must handle the case where the first stage is a freeze? We said we require the first stage to be a ramp. So we can check:
if (stages[0].type !== 'ramp') {
throw new Error("First stage must be a ramp")
}
Also, we must have a last_value after the first ramp? Yes, because the first ramp sets last_value.
However, what if the first ramp has duration 0 and t is not exactly at current_time (which is 0)? Then we might not set last_value? But then the next stage (if freeze) would use last_value which is null? That's a problem.
Example:
stages = [
{ type: 'ramp', start_percent: 0, end_percent: 100, duration: 0 },
{ type: 'freeze', duration: 5 }
]
If t=1, then:
stage1: duration 0, t (1) !== current_time (0) -> we do nothing? Then last_value remains null.
stage2: freeze, t in [0,5) -> return last_value (null) -> error.
So we must set last_value for the 0 duration ramp even if t is not exactly current_time? But the ramp is instantaneous at current_time. If t is not that time, then we are not at the ramp? Then we should not set last_value? But then the next stage doesn't have a value.
Actually, the 0 duration ramp happens at current_time and changes the value at that time. For any time after, the value is the end_percent? But note: the next stage (freeze) starts at current_time (0) and lasts until 5. So for t in [0,5) we are in the freeze and we return the value at the start of the freeze, which should be the value set by the 0 duration ramp.
So we must set last_value to the end_percent of the 0 duration ramp when we pass that point? But we are processing the stages in order. When we process the 0 duration ramp, we set last_value only if t == current_time? That's not enough because for t>current_time, we have passed the 0 duration ramp and the value should be the end_percent.
So we should set last_value to the end_percent of the 0 duration ramp regardless of t? But note: the 0 duration ramp is at current_time. So if t >= current_time, then we have passed the 0 duration ramp? Actually, if t > current_time, then we have passed the 0 duration ramp and the value is the end_percent.
We can change:
if (duration === 0) {
// This ramp is instantaneous at current_time.
// For any t >= current_time, the value after this ramp is end_percent.
// But note: if t == current_time, we are at the moment of the ramp? We want the value to be end_percent at that time? Or we want the value to be the start_percent at the beginning of the ramp and end_percent at the end? But it's instantaneous.
// We can say: at current_time, the value becomes end_percent.
// So if t >= current_time, then we set last_value = end.
// And then we do not advance current_time.
// But then if we have multiple 0 duration ramps at the same current_time, we set last_value multiple times? That's okay.
if (t >= current_time) {
last_value = end
}
// We don't advance current_time.
}
Then, for the example:
stages = [
ramp (0 duration) from 0 to 100 at time 0,
freeze for 5s
]
t=1:
stage1: t>=0 -> set last_value=100.
stage2: freeze, t in [0,5) -> return 100.
That works.
But what if we have:
stages = [
ramp (0 duration) from 0 to 100 at time 0,
ramp (duration 5) from 100 to 200 starting at time 0.
]
t=1:
stage1: set last_value=100 (because t>=0)
stage2: t in [0,5) -> we compute with start=100 (because we set last_value to 100) and end=200, and t=1 -> we return 100 + (200-100)*(1/5) = 120.
That's correct.
But note: for the second ramp, we used last_value=100 as the start, which is correct.
So let's update:
For a ramp with duration 0:
if (t >= current_time) {
last_value = end
}
// We don't advance current_time.
But wait, what if we have two 0 duration ramps at the same current_time?
stage1: ramp (0 duration) from 0 to 100 at time 0.
stage2: ramp (0 duration) from 100 to 200 at time 0.
t=0:
stage1: t>=0 -> last_value=100.
stage2: t>=0 -> last_value=200.
Then we move to the next stage? But there is no next stage? Then we return 200.
That's correct.
But what if the second 0 duration ramp is at a later time? Example:
stage1: ramp (0 duration) from 0 to 100 at time 0.
stage2: ramp (0 duration) from 100 to 200 at time 5.
Then for t=3:
stage1: t>=0 -> last_value=100 (but note: we are at t=3, which is after the first ramp, so we set last_value to 100? But then the second ramp hasn't happened yet? That's wrong.
We must only set last_value for the 0 duration ramp if t >= current_time and we are at the time of the ramp? Actually, the ramp happens at current_time. So if t >= current_time, then we have passed the ramp? But if the next stage is at a later time, then for t between current_time and the next stage, the value should be the end_percent of the 0 duration ramp? Yes.
However, note that the next stage might not start immediately? But in our design, the stages are contiguous. So the next stage starts at current_time (if 0 duration) or at current_time + duration (if duration>0).
In the example:
stage1: 0 duration at time 0 -> ends at 0.
stage2: 0 duration at time 5 -> starts at 0? But wait, stage1 ended at 0, so stage2 starts at 0? That would mean stage2 is at time 0? That's not what we want.
We must advance current_time after a stage (even 0 duration) to the end of that stage? But for 0 duration, the end is current_time? So we don't move.
How do we get to time 5 for the second ramp? We need an intermediate stage that consumes time.
Example:
stage1: ramp (0 duration) at time 0 -> sets value to 100 at time 0.
stage2: freeze for 5s -> from 0 to 5, value is 100.
stage3: ramp (0 duration) at time 5 -> sets value to 200 at time 5.
Then for t=3:
stage1: t>=0 -> set last_value=100 (but note: we are at t=3, which is after stage1 and during stage2? We set last_value to 100 at stage1, but then stage2 will use that value and freeze it until 5.
But in our algorithm, we process stages in order and for each stage we check if t is in the stage's interval.
For stage1 (0 duration): we set last_value=100 because t>=0? But t=3 is after stage1, so we set last_value to 100? That's correct because after stage1 the value is 100.
Then stage2: freeze from 0 to 5, t=3 is in [0,5) -> return 100.
Then we don't process stage3 because we returned.
That's correct.
But what if we have:
stage1: ramp (0 duration) at time 0 -> set to 100.
stage2: freeze for 5s -> [0,5)
stage3: ramp (0 duration) at time 5 -> set to 200.
stage4: freeze for 5s -> [5,10)
For t=3:
stage1: set last_value=100 (because t>=0)
stage2: t in [0,5) -> return 100.
For t=6:
stage1: set last_value=100 (but t>=0, so set to 100? But then we have stage2 and stage3? We must not set last_value to 100 at stage1 for t=6? Because stage1 is at time 0 and we are at time 6, we have passed stage1 and stage2 and stage3? We should have set last_value to 200 by stage3.
The problem: in our current algorithm, for a 0 duration ramp, we set last_value to end if t >= current_time. That means for any t after the ramp, we set last_value to the ramp's end? But then if there are multiple 0 duration ramps, we set last_value multiple times? And the last one that we process (the one with the highest current_time) will be the one that sets last_value? But we are processing in order.
Actually, we are processing stages in order and for each stage we update last_value if it's a 0 duration ramp and t>=current_time. But note: current_time is the start time of the stage. So for a 0 duration ramp at time 0, we set last_value to its end for any t>=0. Then for a 0 duration ramp at time 5, we set last_value to its end for any t>=5.
So for t=6, we would:
stage1: 0 duration at time0 -> t>=0 -> set last_value=100.
stage2: freeze for 5s -> t=6 is not in [0,5) -> we update current_time to 5? Actually, for freeze we update current_time if t>=current_time+duration. So after stage2, current_time=5.
stage3: 0 duration at time5 -> t>=5 -> set last_value=200.
stage4: freeze for 5s -> t=6 in [5,10) -> return 200.
That's correct.
But what about:
stage1: ramp (0 duration) at time0 -> set to 100 for t>=0.
stage2: ramp (0 duration) at time0 -> set to 200 for t>=0.
Then for t=0, we set last_value to 100 and then to 200. So the value at t=0 is 200.
That's correct.
So the rule for 0 duration ramp: if t >= current_time, set last_value = end.
But note: what if we have a 0 duration ramp and then a ramp with duration>0 that starts at the same current_time? Example:
stage1: ramp (0 duration) at time0 -> set to 100 for t>=0.
stage2: ramp (duration 5) from 100 to 200 starting at time0.
For t=0:
stage1: set last_value=100.
stage2: t in [0,5) -> we compute with start=100 (because last_value is 100) and t=0 -> return 100.
That's correct.
So we are good.
However, we must be careful: for a 0 duration ramp, we set last_value even if we are not going to return from that stage? That's okay because we are updating the state for future stages.
Now, what about the start_percent for a ramp that is not the first and has duration>0? We use last_value if start_percent is omitted. But note: last_value might have been set by a 0 duration ramp that happened at the same current_time? That's correct.
Example:
stage1: ramp (0 duration) at time0 -> set to 100.
stage2: ramp (duration 5) from ? to 200 starting at time0.
For stage2, we don't specify start_percent, so we use last_value (100). That's correct.
Now, what about the case where the first ramp has duration>0 and we have t=0? Then we return the start_percent? Yes, because at t=0, we are in the first ramp and we compute with local_t=0 -> start_percent.
So the algorithm:
let stages = config
let current_time = 0
let last_value = null
// Check first stage is ramp
if (stages.length === 0) {
throw new Error("Config must have at least one stage")
}
if (stages[0].type !== 'ramp') {
throw new Error("First stage must be a ramp")
}
for (let i = 0; i < stages.length; i++) {
let stage = stages[i]
if (stage.type === 'ramp') {
let start
if (last_value === null) {
// first ramp
if (stage.start_percent === undefined) {
throw new Error("First ramp must have start_percent")
}
start = stage.start_percent
} else {
start = (stage.start_percent !== undefined) ? stage.start_percent : last_value
}
let end = stage.end_percent
let duration = stage.duration
if (duration === 0) {
if (t >= current_time) {
last_value = end
}
// We don't advance current_time.
} else {
if (t >= current_time && t < current_time + duration) {
let local_t = (t - current_time) / duration
let eased_t = easingFunction(stage.easing || 'linear')(local_t)
return start + (end - start) * eased_t
} else if (t >= current_time + duration) {
last_value = end
current_time += duration
}
}
} else if (stage.type === 'freeze') {
let duration = stage.duration
if (duration <= 0) {
continue
}
if (t >= current_time && t < current_time + duration) {
return last_value
} else if (t >= current_time + duration) {
current_time += duration
}
}
}
return last_value
But note: what if we have a ramp with duration>0 and then a freeze? The freeze uses last_value which is the end of the ramp. That's correct.
What if we have a freeze and then a ramp? The ramp uses last_value (the frozen value) as the start if start_percent is omitted. That's correct.
What if we have a freeze and then a ramp with start_percent specified? Then we use that start_percent, ignoring the frozen value? That's by design.
Now, we need to define the easing functions.
Let's define a map:
const easingFunctions = {
linear: t => t,
easeInQuad: t => t*t,
easeOutQuad: t => t*(2-t),
easeInOutQuad: t => t<0.5 ? 2*t*t : -1+(4-2*t)*t,
// ... others as needed
}
We can also allow a custom function? But the config is JSON, so we can only use named easings.
Alternatively, we can allow a string that is a function name? But we are in JavaScript, so we can have a map.
Let's code accordingly.
We'll create a function:
function createDynamicConfig(stages) {
// Validate stages?
let current_time = 0
let last_value = null
// Check first stage
if (stages.length === 0) {
throw new Error("Config must have at least one stage")
}
if (stages[0].type !== 'ramp') {
throw new Error("First stage must be a ramp")
}
return function(t) {
// We'll reset current_time and last_value for each call? No, we want to compute from the beginning for any t.
// But note: we are iterating stages and updating current_time and last_value. We must reset for each call.
let local_current_time = 0
let local_last_value = null
for (let i = 0; i < stages.length; i++) {
let stage = stages[i]
if (stage.type === 'ramp') {
let start
if (local_last_value === null) {
if (stage.start_percent === undefined) {
throw new Error("First ramp must have start_percent")
}
start = stage.start_percent
} else {
start = (stage.start_percent !== undefined) ? stage.start_percent : local_last_value
}
let end = stage.end_percent
let duration = stage.duration
if (duration === 0) {
if (t >= local_current_time) {
local_last_value = end
}
} else {
if (t >= local_current_time && t < local_current_time + duration) {
let local_t = (t - local_current_time) / duration
let eased_t = easingFunctions[stage.easing || 'linear'](local_t)
return start + (end - start) * eased_t
} else if (t >= local_current_time + duration) {
local_last_value = end
local_current_time += duration
}
}
} else if (stage.type === 'freeze') {
let duration = stage.duration
if (duration <= 0) {
continue
}
if (t >= local_current_time && t < local_current_time + duration) {
return local_last_value
} else if (t >= local_current_time + duration) {
local_current_time += duration
}
}
}
return local_last_value
}
}
However, note: we are using local_current_time and local_last_value and updating them as we go. This is for one call.
But what about the 0 duration ramp? We set local_last_value if t>=local_current_time. But note: if we have two 0 duration ramps at the same local_current_time, we set local_last_value twice? That's okay.
But what if we have:
stage1: ramp (0 duration) at time0 -> set to 100 for t>=0.
stage2: freeze for 5s -> [0,5)
stage3: ramp (0 duration) at time5 -> set to 200 for t>=5.
For t=3:
stage1: set local_last_value=100 (because t>=0)
stage2: t in [0,5) -> return 100.
For t=6:
stage1: set local_last_value=100 (because t>=0) -> but then we have stage2 and stage3? We must update local_current_time and local_last_value accordingly.
Actually, for t=6:
stage1: set local_last_value=100 (t>=0)
stage2: freeze, t=6 is not in [0,5) -> we update local_current_time to 5 (because t>=0+5) and then continue.
stage3: 0 duration at time5 -> t>=5 -> set local_last_value=200.
Then we return local_last_value (200) at the end.
That's correct.
But note: for stage2, when t>=current_time+duration, we update current_time. But we don't update last_value? That's correct because freeze doesn't change the value.
Now, what about the case where we have a ramp with duration>0 and then a freeze, and t is exactly at the end of the ramp?
ramp: [0,10) -> at t=10, we are not in the ramp (because condition is t < current_time+duration). Then we set last_value to end and update current_time to 10.
Then freeze: [10,15) -> at t=10, we are in the freeze and return last_value (which is the end of the ramp). That's correct.
So the condition for the ramp: if (t >= current_time && t < current_time+duration) -> in the ramp.
And for freeze: if (t >= current_time && t < current_time+duration) -> in the freeze.
But note: at the exact current_time+duration, we are not in the stage? That's by design: the stages are half-open intervals [start, end). So at the exact end, we are in the next stage.
This is consistent.
Now, what about t beyond the total time? We return the last_value (which is the value at the end of the last stage). That's acceptable.
Let's test with an example:
stages = [
{ type: 'ramp', start_percent: 0, end_percent: 100, duration: 10 },
{ type: 'freeze', duration: 5 }
]
Total time: 15.
t=0 -> in first ramp, linear: 0.
t=5 -> in first ramp: 0 + (100-0)*(5/10)=50.
t=10 -> not in first ramp (because t<10+? Actually, first ramp is [0,10). At t=10, we are not in the first ramp. Then we set last_value=100 and current_time=10. Then we check freeze: [10,15) -> t=10 is in [10,15)? Yes, because 10>=10 and 10<15. So we return 100.
t=15 -> not in freeze (because 15>=10+5=15? Actually, freeze is [10,15) so 15 is not included. Then we update current_time to 15 and then return last_value (100) at the end.
That's correct.
Now, what if we have a ramp with 0 duration at the beginning and then a freeze?
stages = [
{ type: 'ramp', end_percent: 100, duration: 0 }, // note: we omit start_percent? But we require first ramp to have start_percent? We can change: if it's the first ramp and duration==0, we don't need start_percent? Because we are jumping to end_percent at time0.
But we required first ramp to have start_percent. Let's change: if it's the first ramp and duration==0, we can set the initial value to end_percent? But then what is the start_percent? We don't care because it's instantaneous.
Alternatively, we can allow the first ramp to omit start_percent if duration==0? But then what is the value before time0? We don't care because we start at time0.
Let's adjust: for the first ramp, if duration==0, we don't require start_percent? But then we set the value at time0 to end_percent.
But note: if the first ramp has duration>0, we require start_percent.
So we can change:
if (local_last_value === null) {
if (stage.duration === 0) {
// We don't need start_percent? But we are going to set the value to end_percent at time0.
// However, what if we want to set the value at time0 to end_percent? Then we don't need start_percent.
// But what about the value before time0? We don't care.
// So we can set start = stage.end_percent? But then the ramp from start to end in 0 time? That's just setting to end.
// Actually, we don't use start for 0 duration. So we can skip setting start.
// But we have a variable 'start' that we use in the ramp calculation? For 0 duration we don't use it.
// So we can do:
// if (stage.duration === 0) {
// // We don't need start_percent for the first ramp if duration==0.
// // But we still set last_value to end at time0.
// } else {
// if (stage.start_percent === undefined) {
// throw new Error("First ramp must have start_percent")
// }
// start = stage.start_percent
// }
} else {
if (stage.start_percent === undefined) {
throw new Error("First ramp must have start_percent")
}
start = stage.start_percent
}
}
But then for non-first ramps with duration==0, we don't use start? We only set last_value to end.
So we can restructure:
if (stage.type === 'ramp') {
let end = stage.end_percent
let duration = stage.duration
if (duration === 0) {
if (t >= local_current_time) {
local_last_value = end
}
// We don't use start for 0 duration.
} else {
let start
if (local_last_value === null) {
if (stage.start_percent === undefined) {
throw new Error("First ramp must have start_percent")
}
start = stage.start_percent
} else {
start = (stage.start_percent !== undefined) ? stage.start_percent : local_last_value
}
if (t >= local_current_time && t < local_current_time + duration) {
let local_t = (t - local_current_time) / duration
let eased_t = easingFunctions[stage.easing || 'linear'](local_t)
return start + (end - start) * eased_t
} else if (t >= local_current_time + duration) {
local_last_value = end
local_current_time += duration
}
}
}
This way, for 0 duration ramps we don't require start_percent at all (even for the first). But note: for the first ramp with duration>0, we require start_percent.
However, what if the first ramp is 0 duration and we don't specify start_percent? Then we set the value at time0 to end_percent. That's acceptable.
But what if we have a first ramp with duration>0 and we don't specify start_percent? We throw.
Now, what about a non-first ramp with duration>0 and no start_percent? We use local_last_value.
Let's code accordingly.
We'll also need to handle the case where the config has only one stage and it's a ramp with duration>0? Then for t beyond the duration, we return the end_percent? Yes.
Example:
stages = [
{ type: 'ramp', start_percent: 0, end_percent: 100, duration: 10 }
]
t=15 -> we update local_current_time to 10 and local_last_value to 100, then return 100.
That's correct.
Now, let's code the easing functions.
We'll define:
const easingFunctions = {
linear: t => t,
easeInQuad: t => t * t,
easeOutQuad: t => t * (2 - t),
easeInOutQuad: t => t < 0.5 ? 2 * t * t : -1 + (4 - 2 * t) * t,
easeInCubic: t => t * t * t,
easeOutCubic: t => (--t) * t * t + 1,
easeInOutCubic: t => t < 0.5 ? 4 * t * t * t : (t - 1) * (2 * t - 2) * (2 * t - 2) + 1,
// ... add more as needed
}
We can also allow a custom function? But since the config is JSON, we can only use strings.
Now, let's write the full code.
We'll also validate the config: each stage must have the required properties.
For ramp: must have end_percent and duration. For the first ramp with duration>0, must have start_percent.
For freeze: must have duration.
We can do validation in the createDynamicConfig function.
Let's code accordingly.
We'll create:
function createDynamicConfig(stages) {
// Validate stages array
if (!Array.isArray(stages) || stages.length === 0) {
throw new Error("Config must be a non-empty array")
}
// Check first stage
if (stages[0].type !== 'ramp') {
throw new Error("First stage must be a ramp")
}
// Validate each stage
for (let i = 0; i < stages.length; i++) {
let stage = stages[i]
if (stage.type === 'ramp') {
if (stage.end_percent === undefined) {
throw new Error(`Ramp at index ${i} must have end_percent`)
}
if (stage.duration === undefined) {
throw new Error(`Ramp at index ${i} must have duration`)
}
// For the first ramp with duration>0, check start_percent
if (i === 0 && stage.duration > 0 && stage.start_percent === undefined) {
throw new Error("First ramp with non-zero duration must have start_percent")
}
} else if (stage.type === 'freeze') {
if (stage.duration === undefined) {
throw new Error(`Freeze at index ${i} must have duration`)
}
} else {
throw new Error(`Unknown stage type at index ${i}: ${stage.type}`)
}
}
// Easing functions
const easingFunctions = {
linear: t => t,
easeInQuad: t => t * t,
easeOutQuad: t => t * (2 - t),
easeInOutQuad: t => t < 0.5 ? 2 * t * t : -1 + (4 - 2 * t) * t,
easeInCubic: t => t * t * t,
easeOutCubic: t => (--t) * t * t + 1,
easeInOutCubic: t => t < 0.5 ? 4 * t * t * t : (t - 1) * (2 * t - 2) * (2 * t - 2) + 1,
// Add more if needed
}
return function(t) {
let local_current_time = 0
let local_last_value = null
for (let i = 0; i < stages.length; i++) {
let stage = stages[i]
if (stage.type === 'ramp') {
let end = stage.end_percent
let duration = stage.duration
if (duration === 0) {
if (t >= local_current_time) {
local_last_value = end
}
// We don't advance local_current_time for 0 duration.
} else {
let start
if (local_last_value === null) {
// First ramp with duration>0
start = stage.start_percent
} else {
start = (stage.start_percent !== undefined) ? stage.start_percent : local_last_value
}
if (t >= local_current_time && t < local_current_time + duration) {
let local_t = (t - local_current_time) / duration
let eased_t = easingFunctions[stage.easing || 'linear'](local_t)
return start + (end - start) * eased_t
} else if (t >= local_current_time + duration) {
local_last_value = end
local_current_time += duration
}
}
} else if (stage.type === 'freeze') {
let duration = stage.duration
if (duration <= 0) {
continue
}
if (t >= local_current_time && t < local_current_time + duration) {
return local_last_value
} else if (t >= local_current_time + duration) {
local_current_time += duration
}
}
}
return local_last_value
}
}
Let's test with a few examples.
Example 1:
stages = [
{ type: 'ramp', start_percent: 0, end_percent: 100, duration: 10 },
{ type: 'freeze', duration: 5 }
]
t=0 -> 0
t=5 -> 50
t=10 -> 100 (from freeze? Actually, at t=10 we are in the freeze? The freeze starts at 10? Let's see:
ramp: [0,10) -> at t=10, we are not in the ramp. Then we set last_value=100 and current_time=10.
freeze: [10,15) -> t=10 is in [10,15) -> return 100.
So t=10 returns 100.
t=12 -> 100 (freeze)
t=15 -> 100 (after freeze, we return last_value)
Example 2:
stages = [
{ type: 'ramp', end_percent: 100, duration: 0 },
{ type: 'freeze', duration: 5 }
]
First ramp: duration=0, so for any t>=0, last_value=100.
Then freeze: [0,5) -> for t in [0,5) return 100.
t=0 -> 100
t=3 -> 100
t=5 -> 100 (after freeze, we return last_value which is 100)
Example 3:
stages = [
{ type: 'ramp', start_percent: 0, end_percent: 100, duration: 10 },
{ type: 'ramp', end_percent: 50, duration: 10 }
]
t=0 -> 0
t=5 -> 50
t=10 -> 100 (from first ramp end)
t=15 -> 75 (second ramp: 100 to 50 in 10 seconds, so at 5 seconds into the second ramp: 100 + (50-100)*(5/10)=75)
t=20 -> 50
Example 4:
stages = [
{ type: 'ramp', start_percent: 0, end_percent: 100, duration: 10 },
{ type: 'ramp', end_percent: 50, duration: 0 },
{ type: 'freeze', duration: 5 }
]
At t=10:
first ramp ends -> last_value=100, current_time=10.
second ramp: duration=0, t>=10 -> set last_value=50.
freeze: [10,15) -> return 50.
So t=10 -> 50.
This seems to work.
However, note: for the second ramp (0 duration) we set last_value to 50, but we don't advance current_time. Then the freeze starts at current_time=10 and lasts 5s. So for t in [10,15) we return 50.
But what about t=10.5? Same.
Now, what if we have:
stages = [
{ type: 'ramp', start_percent: 0, end_percent: 100, duration: 10 },
{ type: 'ramp', end_percent: 50, duration: 0 },
{ type: 'ramp', end_percent: 0, duration: 10 }
]
At t=10:
first ramp: ends -> last_value=100, current_time=10.
second ramp: 0 duration -> set last_value=50 (for t>=10)
third ramp: duration=10, start? We use last_value (50) because no start_percent. So from 50 to 0 in 10 seconds.
Then for t=15 (5 seconds into the third ramp):
value = 50 + (0-50)*(5/10) = 25.
That's correct.
Now, what if we have a 0 duration ramp that is not the first and we don't specify start_percent? We use last_value? But we don't use start for 0 duration. So it's okay.
One more edge: what if we have a 0 duration ramp and then a freeze and then a ramp with start_percent specified?
stages = [
{ type: 'ramp', start_percent: 0, end_percent: 100, duration: 10 },
{ type: 'ramp', end_percent: 50, duration: 0 },
{ type: 'freeze', duration: 5 },
{ type: 'ramp', start_percent: 0, end_percent: 100, duration: 10 }
]
At t=10:
first ramp: last_value=100, current_time=10.
second ramp: 0 duration -> set last_value=50.
freeze: [10,15) -> at t=10 we are in the freeze? Actually, the freeze starts at 10 and lasts until 15. So for t in [10,15) we return 50.
Then at t=15:
freeze ends -> current_time=15.
third ramp: start_percent=0, end_percent=100, duration=10. But note: we are at current_time=15 and t=15? Then we are in the third ramp? Actually, the third ramp starts at 15 and lasts until 25.
At t=15, we are in the third ramp and return start_percent (0) because local_t=0.
But wait, the value at the end of the freeze (at t=15) should be 50? Then the ramp starts from 0? That's a jump.
That's by design because we specified start_percent=0.
If we want to continue from 50, we omit start_percent.
So the config is:
[
{ type: 'ramp', start_percent: 0, end_percent: 100, duration: 10 },
{ type: 'ramp', end_percent: 50, duration: 0 }, // jump to 50 at time10
{ type: 'freeze', duration: 5 }, // freeze at 50 until 15
{ type: 'ramp', start_percent: 0, end_percent: 100, duration: 10 } // jump to 0 at time15 and ramp to 100 by 25
]
This is acceptable.
Now, let's code accordingly.
We'll also consider: what if we have a ramp with negative start_percent or end_percent? Or >100? We don't enforce 0-100? The config says percent, but maybe we want to allow over 100? Let's not enforce.
We'll just compute the value as given.
Now, let's write the code.
We'll also add a helper to compute the total time of the config? Not necessary for the function, but might be useful.
We can compute total time by summing the durations of ramps (with duration>0) and freezes. But note: 0 duration ramps don't add time.
But we don't need total time for the function.
Let's code.
I'll create a dynamic configuration system that supports percent ramps (smooth transitions between values) and freezes (holding values constant). This is useful for animations, parameter automation, or any system needing timed value changes.
Architecture Overview
config/
├── stages/ # Sequential stages
│ ├── ramps/ # Smooth transitions
│ └── freezes/ # Value holds
├── easing/ # Interpolation curves
└── global/ # System-wide settings
Core Implementation
// dynamic-config-system.js
/**
* Dynamic Config System with Percent Ramps and Freezes
*/
class DynamicConfigSystem {
constructor(config = {}) {
this.stages = config.stages || [];
this.currentStageIndex = 0;
this.startTime = null;
this.currentValue = 0;
this.isPaused = false;
this.pauseStart = null;
this.totalPausedTime = 0;
// Validation
this._validateConfig();
// Initialize from first stage
if (this.stages.length > 0) {
this._initializeStage(0);
}
}
/**
* Validate configuration structure
*/
_validateConfig() {
if (!Array.isArray(this.stages)) {
throw new Error('Stages must be an array');
}
for (let i = 0; i < this.stages.length; i++) {
const stage = this.stages[i];
if (!stage.type || !['ramp', 'freeze'].includes(stage.type)) {
throw new Error(`Stage ${i}: Invalid type "${stage.type}". Must be 'ramp' or 'freeze'`);
}
if (stage.type === 'ramp') {
if (typeof stage.startPercent !== 'number' ||
typeof stage.endPercent !== 'number' ||
typeof stage.duration !== 'number' || stage.duration < 0) {
throw new Error(`Stage ${i}: Ramp requires valid startPercent, endPercent, and duration`);
}
}
if (stage.type === 'freeze') {
if (typeof stage.duration !== 'number' || stage.duration < 0) {
throw new Error(`Stage ${i}: Freeze requires valid duration`);
}
}
}
}
/**
* Initialize a specific stage
*/
_initializeStage(index) {
if (index >= this.stages.length) {
this.currentStageIndex = this.stages.length - 1;
return;
}
const stage = this.stages[index];
this.currentStageIndex = index;
if (stage.type === 'ramp') {
this.currentValue = stage.startPercent;
this.stageStartTime = this._getCurrentTime();
this.stageDuration = stage.duration;
this.stageEndValue = stage.endPercent;
this.easing = stage.easing || 'linear';
} else if (stage.type === 'freeze') {
// Freezes maintain the previous value
this.stageStartTime = this._getCurrentTime();
this.stageDuration = stage.duration;
}
}
/**
* Get current time (handles pauses)
*/
_getCurrentTime() {
if (this.startTime === null) return 0;
const elapsed = Date.now() - this.startTime - this.totalPausedTime;
return this.isPaused ? this.pauseStart - this.startTime - this.totalPausedTime : elapsed;
}
/**
* Apply easing function to normalized time (0-1)
*/
_applyEasing(t, easingType) {
const easings = {
linear: t => t,
easeInQuad: t => t * t,
easeOutQuad: t => t * (2 - t),
easeInOutQuad: t => t < 0.5 ? 2 * t * t : -1 + (4 - 2 * t) * t,
easeInCubic: t => t * t * t,
easeOutCubic: t => (--t) * t * t + 1,
easeInOutCubic: t => t < 0.5 ? 4 * t * t * t : (t - 1) * (2 * t - 2) * (2 * t - 2) + 1,
// Add more easing functions as needed
};
return (easings[easingType] || easings.linear)(t);
}
/**
* Update system (call this in animation loop)
*/
update() {
if (this.startTime === null) {
this.startTime = Date.now();
}
if (this.isPaused) return this.currentValue;
const currentTime = this._getCurrentTime();
const stage = this.stages[this.currentStageIndex];
if (!stage) return this.currentValue;
const stageElapsed = currentTime - this.stageStartTime;
// Check if current stage is complete
if (stageElapsed >= this.stageDuration) {
// Move to next stage
if (this.currentStageIndex < this.stages.length - 1) {
this._initializeStage(this.currentStageIndex + 1);
return this.update(); // Recursive call for new stage
}
return this.currentValue; // At end of config
}
// Calculate current value based on stage type
if (stage.type === 'ramp') {
const progress = stageElapsed / this.stageDuration;
const easedProgress = this._applyEasing(progress, this.easing);
this.currentValue = this.stageStartValue +
(this.stageEndValue - this.stageStartValue) * easedProgress;
}
// Freeze stages maintain currentValue
return this.currentValue;
}
/**
* Start/resume the system
*/
start() {
if (this.isPaused) {
this.totalPausedTime += Date.now() - this.pauseStart;
this.isPaused = false;
} else if (this.startTime === null) {
this.startTime = Date.now();
}
}
/**
* Pause the system
*/
pause() {
if (!this.isPaused) {
this.pauseStart = Date.now();
this.isPaused = true;
}
}
/**
* Reset to beginning
*/
reset() {
this.startTime = null;
this.currentStageIndex = 0;
this.totalPausedTime = 0;
this.isPaused = false;
this._initializeStage(0);
}
/**
* Get current stage info
*/
getCurrentStage() {
return this.stages[this.currentStageIndex] || null;
}
/**
* Get progress in current stage (0-1)
*/
getStageProgress() {
const currentTime = this._getCurrentTime();
const stage = this.stages[this.currentStageIndex];
if (!stage || this.stageDuration === 0) return 0;
return Math.min(1, (currentTime - this.stageStartTime) / this.stageDuration);
}
/**
* Get overall progress (0-1)
*/
getOverallProgress() {
let totalDuration = 0;
let elapsed = 0;
// Calculate total duration
for (const stage of this.stages) {
totalDuration += stage.duration;
}
if (totalDuration === 0) return 0;
// Calculate elapsed time including current stage
for (let i = 0; i < this.currentStageIndex; i++) {
elapsed += this.stages[i].duration;
}
const currentStage = this.stages[this.currentStageIndex];
if (currentStage) {
elapsed += this._getCurrentTime() - this.stageStartTime;
}
return Math.min(1, elapsed / totalDuration);
}
}
// Export for Node.js or browser
if (typeof module !== 'undefined' && module.exports) {
module.exports = DynamicConfigSystem;
}
Configuration Examples
// config-examples.js
const examples = {
// Simple ramp then freeze
simple: {
stages: [
{ type: 'ramp', startPercent: 0, endPercent: 100, duration: 5000, easing: 'easeOutQuad' },
{ type: 'freeze', duration: 2000 }
]
},
// Multiple ramps with freezes between
complex: {
stages: [
{ type: 'ramp', startPercent: 0, endPercent: 100, duration: 3000 },
{ type: 'freeze', duration: 1000 },
{ type: 'ramp', startPercent: 100, endPercent: 50, duration: 2000, easing: 'easeInOutCubic' },
{ type: 'freeze', duration: 500 },
{ type: 'ramp', startPercent: 50, endPercent: 0, duration: 3000 }
]
},
// Jump with 0-duration ramp
withJump: {
stages: [
{ type: 'ramp', startPercent: 0, endPercent: 100, duration: 2000 },
{ type: 'ramp', startPercent: 100, endPercent: 50, duration: 0 }, // Instant jump
{ type: 'freeze', duration: 1000 },
{ type: 'ramp', startPercent: 50, endPercent: 0, duration: 3000 }
]
},
// Looping configuration
looping: {
stages: [
{ type: 'ramp', startPercent: 0, endPercent: 100, duration: 5000 },
{ type: 'freeze', duration: 1000 },
{ type: 'ramp', startPercent: 100, endPercent: 0, duration: 5000 },
{ type: 'freeze', duration: 1000 }
]
}
};
// Usage example
function demo() {
const configSystem = new DynamicConfigSystem(examples.simple);
// Animation loop
function animate() {
const value = configSystem.update();
console.log(`Current value: ${value.toFixed(2)}%`);
console.log(`Stage: ${configSystem.getCurrentStage()?.type || 'end'}`);
console.log(`Progress: ${(configSystem.getOverallProgress() * 100).toFixed(1)}%`);
console.log('---');
if (configSystem.getOverallProgress() < 1) {
requestAnimationFrame(animate);
}
}
configSystem.start();
animate();
}
React Hook Implementation (Optional)
// useDynamicConfig.js - React hook version
import { useState, useEffect, useRef, useCallback } from 'react';
export function useDynamicConfig(config, autoStart = true) {
const configSystemRef = useRef(null);
const [value, setValue] = useState(0);
const [isRunning, setIsRunning] = useState(false);
const [progress, setProgress] = useState(0);
const [currentStage, setCurrentStage] = useState(null);
// Initialize config system
useEffect(() => {
configSystemRef.current = new DynamicConfigSystem(config);
return () => {
if (configSystemRef.current) {
configSystemRef.current.reset();
}
};
}, [config]);
// Animation loop
useEffect(() => {
if (!configSystemRef.current || !isRunning) return;
let animationFrameId;
const animate = () => {
const newValue = configSystemRef.current.update();
setValue(newValue);
setProgress(configSystemRef.current.getOverallProgress());
setCurrentStage(configSystemRef.current.getCurrentStage());
if (configSystemRef.current.getOverallProgress() < 1) {
animationFrameId = requestAnimationFrame(animate);
} else {
setIsRunning(false);
}
};
animationFrameId = requestAnimationFrame(animate);
return () => {
if (animationFrameId) {
cancelAnimationFrame(animationFrameId);
}
};
}, [isRunning]);
const start = useCallback(() => {
if (configSystemRef.current) {
configSystemRef.current.start();
setIsRunning(true);
}
}, []);
const pause = useCallback(() => {
if (configSystemRef.current) {
configSystemRef.current.pause();
setIsRunning(false);
}
}, []);
const reset = useCallback(() => {
if (configSystemRef.current) {
configSystemRef.current.reset();
setValue(0);
setProgress(0);
setCurrentStage(null);
setIsRunning(false);
}
}, []);
return {
value,
progress,
currentStage,
isRunning,
start,
pause,
reset,
system: configSystemRef.current
};
}
Usage Example (Browser)
<!DOCTYPE html>
<html>
<head>
<title>Dynamic Config Demo</title>
<style>
.demo-container {
max-width: 800px;
margin: 50px auto;
padding: 20px;
}
.progress-bar {
width: 100%;
height: 30px;
background: #eee;
margin: 20px 0;
border-radius: 15px;
overflow: hidden;
}
.progress-fill {
height: 100%;
background: linear-gradient(90deg, #4CAF50, #8BC34A);
width: 0%;
transition: width 0.1s;
}
.value-display {
font-size: 2em;
text-align: center;
margin: 20px 0;
}
.controls {
display: flex;
gap: 10px;
margin: 20px 0;
}
button {
padding: 10px 20px;
font-size: 16px;
cursor: pointer;
}
</style>
</head>
<body>
<div class="demo-container">
<h1>Dynamic Config System Demo</h1>
<div class="value-display">
Value: <span id="value">0</span>%
</div>
<div class="progress-bar">
<div class="progress-fill" id="progressFill"></div>
</div>
<div>Stage: <span id="stage">-</span></div>
<div>Progress: <span id="progress">0</span>%</div>
<div class="controls">
<button onclick="startDemo()">Start</button>
<button onclick="pauseDemo()">Pause</button>
<button onclick="resetDemo()">Reset</button>
</div>
<div>
<h3>Select Configuration:</h3>
<select onchange="loadConfig(this.value)">
<option value="simple">Simple Ramp + Freeze</option>
<option value="complex">Complex Multiple Stages</option>
<option value="withJump">With Jump</option>
<option value="looping">Looping</option>
</select>
</div>
</div>
<script src="dynamic-config-system.js"></script>
<script>
let configSystem;
let animationId;
function loadConfig(configName) {
const configs = {
simple: {
stages: [
{ type: 'ramp', startPercent: 0, endPercent: 100, duration: 5000, easing: 'easeOutQuad' },
{ type: 'freeze', duration: 2000 }
]
},
complex: {
stages: [
{ type: 'ramp', startPercent: 0, endPercent: 100, duration: 3000 },
{ type: 'freeze', duration: 1000 },
{ type: 'ramp', startPercent: 100, endPercent: 50, duration: 2000, easing: 'easeInOutCubic' },
{ type: 'freeze', duration: 500 },
{ type: 'ramp', startPercent: 50, endPercent: 0, duration: 3000 }
]
},
withJump: {
stages: [
{ type: 'ramp', startPercent: 0, endPercent: 100, duration: 2000 },
{ type: 'ramp', startPercent: 100, endPercent: 50, duration: 0 },
{ type: 'freeze', duration: 1000 },
{ type: 'ramp', startPercent: 50, endPercent: 0, duration: 3000 }
]
},
looping: {
stages: [
{ type: 'ramp', startPercent: 0, endPercent: 100, duration: 5000 },
{ type: 'freeze', duration: 1000 },
{ type: 'ramp', startPercent: 100, endPercent: 0, duration: 5000 },
{ type: 'freeze', duration: 1000 }
]
}
};
resetDemo();
configSystem = new DynamicConfigSystem(configs[configName]);
updateDisplay();
}
function animate() {
if (configSystem && !configSystem.isPaused) {
const value = configSystem.update();
updateDisplay();
if (configSystem.getOverallProgress() < 1) {
animationId = requestAnimationFrame(animate);
}
}
}
function updateDisplay() {
if (!configSystem) return;
document.getElementById('value').textContent = configSystem.currentValue.toFixed(1);
document.getElementById('progressFill').style.width =
`${configSystem.getOverallProgress() * 100}%`;
document.getElementById('progress').textContent =
`${(configSystem.getOverallProgress() * 100).toFixed(1)}`;
document.getElementById('stage').textContent =
configSystem.getCurrentStage()?.type || 'complete';
}
function startDemo() {
if (configSystem) {
configSystem.start();
animate();
}
}
function pauseDemo() {
if (configSystem) {
configSystem.pause();
if (animationId) {
cancelAnimationFrame(animationId);
}
}
}
function resetDemo() {
if (animationId) {
cancelAnimationFrame(animationId);
}
if (configSystem) {
configSystem.reset();
updateDisplay();
}
}
// Load default config on page load
window.onload = () => loadConfig('simple');
</script>
</body>
</html>
Key Features
- Percent Ramps: Smooth transitions between percentage values with customizable easing
- Freezes: Hold values constant for specified durations
- Zero-duration Ramps: Instant jumps (useful for step changes)
- Easing Functions: Built-in support for common easing curves
- Stage Management: Sequential execution with proper timing
- Pause/Resume: Full pause functionality with accurate time tracking
- Progress Tracking: Both stage-level and overall progress
- Validation: Configuration structure validation
Extending the System
To add more features:
// Add custom easing
DynamicConfigSystem.prototype.addEasing = function(name, fn) {
this.easings[name] = fn;
};
// Add parallel stages (for complex configurations)
class ParallelStage {
constructor(stages) {
this.stages = stages;
this.type = 'parallel';
}
}
// Add conditional stages
class ConditionalStage {
constructor(condition, thenStage, elseStage) {
this.condition = condition;
this.thenStage = thenStage;
this.elseStage = elseStage;
this.type = 'conditional';
}
}
This system provides a flexible foundation for any application needing timed value changes with smooth transitions and holds. The percent-based approach makes it easy to work with normalized values (0-100%) that can be scaled to any actual range.