CertainLach / jrsonnet

Rust implementation of Jsonnet language
MIT License
290 stars 33 forks source link

Break the loop in jsonnet #161

Closed redoC-A2k closed 1 month ago

redoC-A2k commented 2 months ago

I want to break loop ( it can be through std.map function or for loop) in jsonnet ? Isn't there any keyword or functionality like "break" keyword in jsonnet similar to conventional loops . If not is it possible to modify source code of jrsonnet so as to have similar functionality ?

CertainLach commented 2 months ago

Jsonnet is functional, and break is not something that makes sense here

Instead you're supposed to write code over combinators, where everything is lazy and thus unreachable parts will just not be executed.

local takeUntil(arr, until) = std.foldl(
   function(acc,i) if acc.finished then acc else acc {out+: [i], finished: i == until},
   arr,
   {out: [], finished: false}
).out;

local mapped = std.map(function(a) a * 2, [1, 2, 3, 4, 5, 6, error "will not reach this element"]);
takeUntil(mapped, 6) == [2, 4, 6]
redoC-A2k commented 1 month ago

Thanks a lot for letting me know about std.foldl using that function we achived what we wanted to do .