passsy / prefer-for-loopr3
Prefer a for-loop over forEach
PublicWrite a plain for loop instead of forEach, because forEach allocates an unnecessary lambda; for transformations use map, flatMap or reduce.
tests, run by the registry7 passed · slowest 4.0 ms
✓fires3.2 ms
fires on a forEach the agent writes
write lib/notify.dartfired: line 2
void notifyAll(List<Listener> listeners) {
listeners.forEach((it) => it.notify());
}✓quiet3.3 ms
stays quiet on a for loop
write lib/notify.dartstayed quiet
void notifyAll(List<Listener> listeners) {
for (final it in listeners) {
it.notify();
}
}✓quiet3.3 ms
stays quiet on forEach in a comment
write lib/hint.dartstayed quiet
// Do not use .forEach( here.
final hint = 'use a for loop';✓quiet3.2 ms
stays quiet on a forEach the agent did not write
write lib/notify.dart · wrote line 1stayed quiet
void notifyAll(List<Listener> listeners) {
listeners.forEach((it) => it.notify());
}✓skips0.0 ms
stays quiet when the agent only reads the file
read lib/notify.dartno handler of the detector wants this event
void notifyAll(List<Listener> listeners) {
listeners.forEach((it) => it.notify());
}✓fires4.0 ms
points at the principle when the user mentions forEach
prompt · in fixtures/dart_appfired: "forEach"
Use forEach to notify the listeners✓quiet3.1 ms
stays quiet on the same words outside a Dart project
promptstayed quiet
Use forEach to notify the listenersdetector.test.tseach detect() call runs the real detectorEdit
import { expect, test } from "vitest";
import { detect, edit, prompt, read, source, write } from "@wellactually/sdk/v3/test";
const loop = source`
void notifyAll(List<Listener> listeners) {
listeners.forEach((it) => it.notify());
}
`;
test("fires on a forEach the agent writes", () => {
expect(detect(write("lib/notify.dart", loop))).toEqual([{ line: 2 }]);
});
test("stays quiet on a for loop", () => {
const code = source`
void notifyAll(List<Listener> listeners) {
for (final it in listeners) {
it.notify();
}
}
`;
expect(detect(write("lib/notify.dart", code))).toEqual([]);
});
test("stays quiet on forEach in a comment", () => {
const code = source`
// Do not use .forEach( here.
final hint = 'use a for loop';
`;
expect(detect(write("lib/hint.dart", code))).toEqual([]);
});
test("stays quiet on a forEach the agent did not write", () => {
expect(detect(edit("lib/notify.dart", loop, { written: "void notifyAll(List<Listener> listeners) {" }))).toEqual([]);
});
test("stays quiet when the agent only reads the file", () => {
expect(detect(read("lib/notify.dart", loop))).toEqual([]);
});
const dartApp = { project: "fixtures/dart_app" };
test("points at the principle when the user mentions forEach", () => {
expect(detect(prompt("Use forEach to notify the listeners"), dartApp)).toEqual([{ match: "forEach", depth: "pointer" }]);
});
test("stays quiet on the same words outside a Dart project", () => {
expect(detect(prompt("Use forEach to notify the listeners"))).toEqual([]);
});