Skip to content

Commit 8646b1e

Browse files
committed
feat: add shuffle
1 parent 646407a commit 8646b1e

File tree

1 file changed

+20
-1
lines changed

1 file changed

+20
-1
lines changed

frontend/src/js/workers/templating-worker.js

Lines changed: 20 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -136,13 +136,32 @@ env.addExtension('DataImportExtension', new DataImportExtension());
136136
env.addExtension('JavascriptExecuteExtension', new JavascriptExecuteExtension());
137137
env.addExtension('AIExtension', new AIExtension());
138138

139+
env.addFilter('shuffle', (array) => {
140+
let currentIndex = array.length,
141+
temporaryValue,
142+
randomIndex;
143+
144+
// While there remain elements to shuffle...
145+
while (0 !== currentIndex) {
146+
// Pick a remaining element...
147+
randomIndex = Math.floor(Math.random() * currentIndex);
148+
currentIndex -= 1;
149+
150+
// And swap it with the current element.
151+
temporaryValue = array[currentIndex];
152+
array[currentIndex] = array[randomIndex];
153+
array[randomIndex] = temporaryValue;
154+
}
155+
156+
return array;
157+
});
139158
env.addFilter('markdown', (md) => new nunjucks.runtime.SafeString(markdown.render(md)));
140159
env.addFilter('markdowni', (md) => new nunjucks.runtime.SafeString(markdown.renderInline(md)));
141160
env.addFilter('json', (data) => new nunjucks.runtime.SafeString(JSON.stringify(data)));
142161
env.addFilter(
143162
'source',
144163
(source, cb) => {
145-
// we can't use api here as mithrils request functions don't work in web-workers,
164+
// We can't use api here as mithrils request functions don't work in web-workers,
146165
// so we just use a simple fetch.
147166
fetch('/api/getEntries', {
148167
method: 'POST',

0 commit comments

Comments
 (0)