nebius/SWE-rebench-V2-PRs huggingface dataset:
Repository: jlongster/prettier
Pull request #114 (2017-01-11 16:05:47)

docs: add globbing example
Although prettier lacks options to filter project files to format by itself, most shells allow to submit multiple files with a filename expansion. Add an example using bash.


Patch:
diff --git a/README.md b/README.md
index 8ee5e736a..c20786860 100644
--- a/README.md
+++ b/README.md
@@ -97,13 +97,19 @@ Run prettier through the CLI with this script. Run it without any
 arguments to see the options.
 
 To format a file in-place, use `--write`. While this is in beta you
-should probably commit your code before doing that. In the future we
-will have better support for formatting whole projects.
+should probably commit your code before doing that.
 
 ```js
-prettier <opts> <filename>
+prettier [opts] [filename ...]
 ```
 
+For example, you could format your source using bash filename expansion:
+```bash
+prettier --write src/**/*.js bin/*.js
+```
+
+In the future we will have better support for formatting whole projects.
+
 ### API
 
 The API is a single function exported as `format`. The options
diff --git a/bin/prettier.js b/bin/prettier.js
index 2832476ed..31c8bef5d 100755
--- a/bin/prettier.js
+++ b/bin/prettier.js
@@ -17,7 +17,7 @@ const write = argv["write"];
 
 if (!filenames.length) {
   console.log(
-    "Usage: prettier [opts] [filename]\n\n" +
+    "Usage: prettier [opts] [filename ...]\n\n" +
     "Available options:\n" +
     "  --write              Edit the file in-place (beware!)\n" +
     "  --print-width <int>  Specify the length of line that the printer will wrap on. Defaults to 80.\n" +
@@ -32,10 +32,6 @@ if (!filenames.length) {
 
 filenames.forEach(filename => {
   fs.readFile(filename, "utf8", (err, input) => {
-    if (write) {
-      console.log(file);
-    }
-
     if (err) {
       console.error("Unable to read file: " + filename + "\n" + err);
       // Don't exit the process if one file failed
diff --git a/src/printer.js b/src/printer.js
index 9e41a6a39..52b5adeee 100644
--- a/src/printer.js
+++ b/src/printer.js
@@ -336,10 +336,10 @@ function genericPrintNoParens(path, options, print) {
       ])));
     }
 
-    parts.push(" =>");
+    parts.push(" => ");
 
     return conditionalGroup([
-      concat([ concat(parts), " ", path.call(print, "body") ]),
+      concat([ concat(parts), path.call(print, "body") ]),
       concat([ concat(parts),
                indent(options.tabWidth,
                       concat([line, path.call(print, "body")]))])


Test patch:
diff --git a/tests/predicates-parsing/__snapshots__/jsfmt.spec.js.snap b/tests/predicates-parsing/__snapshots__/jsfmt.spec.js.snap
index 0bb77ba91..9b27dbfff 100644
--- a/tests/predicates-parsing/__snapshots__/jsfmt.spec.js.snap
+++ b/tests/predicates-parsing/__snapshots__/jsfmt.spec.js.snap
@@ -113,7 +113,7 @@ var a1 = (x: mixed): %checks => x !== null;
 
 (x): %checks => x !== null;
 
-const insert_a_really_big_predicated_arrow_function_name_here = (x): %checks =>
+const insert_a_really_big_predicated_arrow_function_name_here = (x): %checks => 
   x !== null;
 
 declare var x;
Repository: jlongster/prettier
Pull request #157 (2017-01-12 20:00:45)

Fix misprinting of computed properties in method chains.
Supersedes https://github.com/jlongster/prettier/pull/108 with fixes to get it in.


Patch:
diff --git a/src/printer.js b/src/printer.js
index 5fd4d66f8..b121e7d51 100644
--- a/src/printer.js
+++ b/src/printer.js
@@ -1968,7 +1968,7 @@ function printMemberChain(node, options, print) {
   // easily analyze.
   while (curr.type === "CallExpression" &&
     curr.callee.type === "MemberExpression") {
-    nodes.push({property: curr.callee.property, call: curr});
+    nodes.push({member: curr.callee, call: curr});
     curr = curr.callee.object;
   }
   nodes.reverse();
@@ -1995,7 +1995,7 @@ function printMemberChain(node, options, print) {
   if (hasMultipleLookups) {
     const currPrinted = print(FastPath.from(curr));
     const nodesPrinted = nodes.map(node => ({
-      property: print(FastPath.from(node.property)),
+      property: printMemberLookup(FastPath.from(node.member), print),
       args: printArgumentsList(FastPath.from(node.call), options, print)
     }));
     const fullyExpanded = concat([
@@ -2004,7 +2004,7 @@ function printMemberChain(node, options, print) {
         nodesPrinted.map(node => {
           return indent(
             options.tabWidth,
-            concat([ hardline, ".", node.property, node.args ])
+            concat([ hardline, node.property, node.args ])
           );
         })
       )
@@ -2026,7 +2026,7 @@ function printMemberChain(node, options, print) {
           currPrinted,
           concat(
             nodesPrinted.map(node => {
-              return concat([ ".", node.property, node.args ]);
+              return concat([ node.property, node.args ]);
             })
           )
         ]),


Test patch:
diff --git a/tests/prettier/__snapshots__/jsfmt.spec.js.snap b/tests/prettier/__snapshots__/jsfmt.spec.js.snap
index 287f35f05..494775736 100644
--- a/tests/prettier/__snapshots__/jsfmt.spec.js.snap
+++ b/tests/prettier/__snapshots__/jsfmt.spec.js.snap
@@ -13,6 +13,18 @@ function fn() {
 "
 `;
 
+exports[`test method-chain.js 1`] = `
+"method().then(x => x)
+  [\"abc\"](x => x)
+  [abc](x => x);
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+method()
+  .then(x => x)
+  [\"abc\"](x => x)
+  [abc](x => x);
+"
+`;
+
 exports[`test exports.js 1`] = `
 "export { value1, value2 as value2_renamed, value3, value4 as value4_renamed, value5 } from \"exports\";
 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
diff --git a/tests/prettier/method-chain.js b/tests/prettier/method-chain.js
new file mode 100644
index 000000000..05b88058f
--- /dev/null
+++ b/tests/prettier/method-chain.js
@@ -0,0 +1,3 @@
+method().then(x => x)
+  ["abc"](x => x)
+  [abc](x => x);
Repository: jlongster/prettier
Pull request #343 (2017-01-19 22:28:04)

Add semicolon to more default exports
In particular, all `export default [...]`s will be followed by semicolons unless [...] is a .

Now *no* default-exported functions have semicolons. Previously unnamed or async functions would.

This is now in accord with the spec (i.e., has a semicolon if and only if the spec requires one [in the absence of ASI]), but people might find it surprising that there's no semicolon in

```js
export default function() {
  foo();
}
```

Previously: #22, #101, #287.


Patch:
diff --git a/src/printer.js b/src/printer.js
index 82635eecd..345ab45fe 100644
--- a/src/printer.js
+++ b/src/printer.js
@@ -1823,9 +1823,9 @@ function printExportDeclaration(path, options, print) {
 
     if (
       decl.type === "ExportDefaultDeclaration" &&
-        (decl.declaration.type == "Identifier" ||
-          decl.declaration.type === "CallExpression" ||
-          typeIsFunction(decl.declaration.type))
+        (decl.declaration.type !== "ClassDeclaration" &&
+          decl.declaration.type !== "FunctionDeclaration" &&
+          decl.declaration.type !== "FunctionExpression")
     ) {
       parts.push(";");
     }


Test patch:
diff --git a/tests/es6modules/__snapshots__/jsfmt.spec.js.snap b/tests/es6modules/__snapshots__/jsfmt.spec.js.snap
index efd59b9c1..6d3b824a2 100644
--- a/tests/es6modules/__snapshots__/jsfmt.spec.js.snap
+++ b/tests/es6modules/__snapshots__/jsfmt.spec.js.snap
@@ -324,7 +324,7 @@ export var str = \'asdf\';
 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 /* @flow */
 
-export default 42
+export default 42;
 export var str = \"asdf\";
 "
 `;
@@ -1366,7 +1366,7 @@ exports[`test export_default_function_expression.js 1`] = `
 "export default (function() {});
 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 export default function() {
-};
+}
 "
 `;
 
diff --git a/tests/import_typeof/__snapshots__/jsfmt.spec.js.snap b/tests/import_typeof/__snapshots__/jsfmt.spec.js.snap
index 39cb63395..e67223f96 100644
--- a/tests/import_typeof/__snapshots__/jsfmt.spec.js.snap
+++ b/tests/import_typeof/__snapshots__/jsfmt.spec.js.snap
@@ -102,7 +102,7 @@ export default 42;
 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 /* @flow */
 
-export default 42
+export default 42;
 "
 `;
Repository: jlongster/prettier
Pull request #403 (2017-01-22 23:35:26)

Also do the class extend parenthesis for class expressions


Patch:
diff --git a/src/fast-path.js b/src/fast-path.js
index 89a955529..bd288e3e0 100644
--- a/src/fast-path.js
+++ b/src/fast-path.js
@@ -195,7 +195,7 @@ FPp.needsParens = function(assumeExpressionContext) {
   // Add parens around the extends clause of a class. It is needed for almost
   // all expressions.
   if (
-    parent.type === "ClassDeclaration" &&
+    (parent.type === "ClassDeclaration" || parent.type === "ClassExpression") &&
       parent.superClass === node && (
         node.type === "ArrowFunctionExpression" ||
         node.type === "AssignmentExpression" ||


Test patch:
diff --git a/tests/class_extends/__snapshots__/jsfmt.spec.js.snap b/tests/class_extends/__snapshots__/jsfmt.spec.js.snap
index fe29f87d4..4b6925214 100644
--- a/tests/class_extends/__snapshots__/jsfmt.spec.js.snap
+++ b/tests/class_extends/__snapshots__/jsfmt.spec.js.snap
@@ -54,6 +54,8 @@ function* f() {
   // Flow has a bug parsing it.
   // class a extends (yield 1) {}
 }
+
+x = class extends (++b) {}
 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 // \"ArrowFunctionExpression\"
 class a extends (() => {
@@ -112,5 +114,7 @@ function* f() {
   // Flow has a bug parsing it.
   // class a extends (yield 1) {}
 }
+
+x = class extends (++b) {};
 "
 `;
diff --git a/tests/class_extends/extends.js b/tests/class_extends/extends.js
index 6debb835b..d9f3b581e 100644
--- a/tests/class_extends/extends.js
+++ b/tests/class_extends/extends.js
@@ -53,3 +53,5 @@ function* f() {
   // Flow has a bug parsing it.
   // class a extends (yield 1) {}
 }
+
+x = class extends (++b) {}
Repository: jlongster/prettier
Pull request #408 (2017-01-23 00:16:52)

Add parenthesis for arrow function inside of ternary
This one is really weird

```js
if (() => {} ? 1 : 0) {}
```

parses fine but

```js
if (() => {
} ? 1 : 0) {}
```

is a syntax error. Let's always add a parenthesis.

Note that no one is every going to write this in practice, this is really useless :p


Patch:
diff --git a/src/fast-path.js b/src/fast-path.js
index 36b55f3a8..d95a1c8c7 100644
--- a/src/fast-path.js
+++ b/src/fast-path.js
@@ -403,6 +403,11 @@ FPp.needsParens = function(assumeExpressionContext) {
       }
 
       switch (parent.type) {
+        case "ConditionalExpression":
+          if (parent.test === node) {
+            return true;
+          }
+
         case "ExportDefaultDeclaration":
           return node.type !== "ArrowFunctionExpression";
 


Test patch:
diff --git a/tests/arrows/__snapshots__/jsfmt.spec.js.snap b/tests/arrows/__snapshots__/jsfmt.spec.js.snap
index 8ae8dc655..00375d891 100644
--- a/tests/arrows/__snapshots__/jsfmt.spec.js.snap
+++ b/tests/arrows/__snapshots__/jsfmt.spec.js.snap
@@ -33,6 +33,7 @@ export default (() => {})();
 (() => {})()\`\`;
 (() => {})\`\`;
 new (() => {});
+if ((() => {}) ? 1 : 0) {}
 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 (a => {
 }).length;
@@ -46,6 +47,9 @@ export default (() => {
 })\`\`;
 new (() => {
 })();
+if ((() => {
+  }) ? 1 : 0) {
+}
 "
 `;
 
diff --git a/tests/arrows/arrow_function_expression.js b/tests/arrows/arrow_function_expression.js
index 9b579fe04..968072fbc 100644
--- a/tests/arrows/arrow_function_expression.js
+++ b/tests/arrows/arrow_function_expression.js
@@ -4,3 +4,4 @@ export default (() => {})();
 (() => {})()``;
 (() => {})``;
 new (() => {});
+if ((() => {}) ? 1 : 0) {}
Repository: jlongster/prettier
Pull request #557 (2017-02-01 23:16:48)

[JSX] Handle non-breaking space
addresses https://github.com/jlongster/prettier/issues/547

raises one or two minor questions, I think

rattrayalex: ping @vjeux 

Patch:
diff --git a/src/printer.js b/src/printer.js
index ec13aa8bd..061b58db1 100644
--- a/src/printer.js
+++ b/src/printer.js
@@ -2208,9 +2208,10 @@ function printJSXChildren(path, options, print) {
         // correctly escaped (since it parsed).
         // We really want to use value and re-escape it ourself when possible
         // though.
-        const value = options.parser === "flow"
+        const partiallyEscapedValue = options.parser === "flow"
           ? child.raw
           : util.htmlEscapeInsideAngleBracket(child.value);
+        const value = partiallyEscapedValue.replace(/\u00a0/g, '&nbsp;');
 
         if (/\S/.test(value)) {
           // treat each line of text as its own entity


Test patch:
diff --git a/tests/jsx_escape/__snapshots__/jsfmt.spec.js.snap b/tests/jsx_escape/__snapshots__/jsfmt.spec.js.snap
index 0a79acf98..dc6d640f0 100644
--- a/tests/jsx_escape/__snapshots__/jsfmt.spec.js.snap
+++ b/tests/jsx_escape/__snapshots__/jsfmt.spec.js.snap
@@ -11,3 +11,38 @@ exports[`test escape.js 2`] = `
 <div>&lt;</div>;
 "
 `;
+
+exports[`test nbsp.js 1`] = `
+"many_nbsp = <div>&nbsp; &nbsp; </div>
+single_nbsp = <div>&nbsp;</div>
+many_raw_nbsp = <div>   </div>
+
+
+amp = <span>foo &amp; bar</span>
+raw_amp = <span>foo & bar</span>
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+many_nbsp = <div>&nbsp; &nbsp; </div>;
+single_nbsp = <div>&nbsp;</div>;
+many_raw_nbsp = <div>&nbsp;&nbsp;&nbsp;</div>;
+amp = <span>foo &amp; bar</span>;
+raw_amp = <span>foo & bar</span>;
+"
+`;
+
+exports[`test nbsp.js 2`] = `
+"many_nbsp = <div>&nbsp; &nbsp; </div>
+single_nbsp = <div>&nbsp;</div>
+many_raw_nbsp = <div>   </div>
+
+
+amp = <span>foo &amp; bar</span>
+raw_amp = <span>foo & bar</span>
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+many_nbsp = <div>&nbsp; &nbsp; </div>;
+single_nbsp = <div>&nbsp;</div>;
+many_raw_nbsp = <div>&nbsp;&nbsp;&nbsp;</div>;
+
+amp = <span>foo & bar</span>;
+raw_amp = <span>foo & bar</span>;
+"
+`;
diff --git a/tests/jsx_escape/jsfmt.spec.js b/tests/jsx_escape/jsfmt.spec.js
index d5ec770a9..7b8a9e6ab 100644
--- a/tests/jsx_escape/jsfmt.spec.js
+++ b/tests/jsx_escape/jsfmt.spec.js
@@ -1,2 +1,2 @@
-run_spec(__dirname);
+run_spec(__dirname, {parser: 'flow'});
 run_spec(__dirname, {parser: 'babylon'});
diff --git a/tests/jsx_escape/nbsp.js b/tests/jsx_escape/nbsp.js
new file mode 100644
index 000000000..87f6989a1
--- /dev/null
+++ b/tests/jsx_escape/nbsp.js
@@ -0,0 +1,7 @@
+many_nbsp = <div>&nbsp; &nbsp; </div>
+single_nbsp = <div>&nbsp;</div>
+many_raw_nbsp = <div>   </div>
+
+
+amp = <span>foo &amp; bar</span>
+raw_amp = <span>foo & bar</span>
Repository: jlongster/prettier
Pull request #720 (2017-02-15 20:29:38)

[Docs]: update Readme to reference VS extension
Added a link to Mads Kristensen's new VS extension for prettier


Patch:
diff --git a/README.md b/README.md
index d408e9786..2610fc416 100644
--- a/README.md
+++ b/README.md
@@ -200,6 +200,10 @@ Can also be installed using `ext install prettier-vscode`
 
 [Check repository for configuration and shortcuts](https://github.com/esbenp/prettier-vscode)
 
+### Visual Studio
+
+Install the [JavaScript Prettier extension](https://github.com/madskristensen/JavaScriptPrettier)
+
 ### Sublime Text
 
 Sublime Text support is available through Package Control and 
diff --git a/src/printer.js b/src/printer.js
index 0acad6736..e8bfe91be 100644
--- a/src/printer.js
+++ b/src/printer.js
@@ -376,6 +376,10 @@ function genericPrintNoParens(path, options, print) {
       return join(" ", parts);
     case "ImportSpecifier":
       if (n.imported) {
+        if (n.importKind) {
+          parts.push(path.call(print, "importKind"), " ");
+        }
+
         parts.push(path.call(print, "imported"));
 
         if (n.local && n.local.name !== n.imported.name) {


Test patch:
diff --git a/tests/flow/import_type/__snapshots__/jsfmt.spec.js.snap b/tests/flow/import_type/__snapshots__/jsfmt.spec.js.snap
index 0beb91ee7..059cd220d 100644
--- a/tests/flow/import_type/__snapshots__/jsfmt.spec.js.snap
+++ b/tests/flow/import_type/__snapshots__/jsfmt.spec.js.snap
@@ -345,6 +345,21 @@ function foo() {
 "
 `;
 
+exports[`test import_type_specifier.js 1`] = `
+"/**
+ * @flow
+ */
+
+import { Foo, type Baz } from \"../module\";
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+/**
+ * @flow
+ */
+
+import { Foo, type Baz } from \"../module\";
+"
+`;
+
 exports[`test issue-359.js 1`] = `
 "/* @flow */
 
diff --git a/tests/flow/import_type/import_type_specifier.js b/tests/flow/import_type/import_type_specifier.js
new file mode 100644
index 000000000..4e5d1bfae
--- /dev/null
+++ b/tests/flow/import_type/import_type_specifier.js
@@ -0,0 +1,5 @@
+/**
+ * @flow
+ */
+
+import { Foo, type Baz } from "../module";
Repository: tableauio/tableau
Pull request #103 (2024-06-01 08:57:35)

fix(xml): syntax error line number not right

huieric: close #102

Patch:
diff --git a/internal/importer/xml.go b/internal/importer/xml.go
index b2888c1..15ccd3f 100644
--- a/internal/importer/xml.go
+++ b/internal/importer/xml.go
@@ -1,6 +1,7 @@
 package importer
 
 import (
+	"bufio"
 	"bytes"
 	"encoding/xml"
 	"fmt"
@@ -53,7 +54,7 @@ func init() {
 	// 		<Weight Num="map<uint32, Weight>"/>
 	// </Server>
 	// -->
-	metasheetRegexp = regexp.MustCompile(fmt.Sprintf(`<!--\s+(<%v(>(\s+`+metasheetItemBlock+`\s+)*</%v>|\s*/>)(.*\n)+?)-->`, book.MetasheetName, book.MetasheetName))
+	metasheetRegexp = regexp.MustCompile(fmt.Sprintf(`<!--\s+(<%v(>(\s+`+metasheetItemBlock+`\s+)*</%v>|\s*/>)(.*\n)+?)-->\s*\n`, book.MetasheetName, book.MetasheetName))
 }
 
 // TODO: options
@@ -85,7 +86,16 @@ func splitRawXML(rawXML string) (metasheet, content string) {
 	if len(matches) < 2 {
 		return "", rawXML
 	}
-	content = strings.ReplaceAll(rawXML, matches[0], "")
+	scanner := bufio.NewScanner(strings.NewReader(matches[0]))	
+	emptyLines := ""
+	for scanner.Scan() {
+		emptyLines += "\n"
+	}
+	if err := scanner.Err(); err != nil {
+		log.Panicf("scanner err:%v", err)
+		return "", rawXML
+	}
+	content = strings.ReplaceAll(rawXML, matches[0], emptyLines)
 	metasheet = xmlProlog + "\n" + escapeAttrs(strings.ReplaceAll(matches[1], book.MetasheetName, atTableauDisplacement))
 	return metasheet, content
 }
@@ -198,7 +208,7 @@ func readXMLFile(metasheet, content string, newBook *book.Book, mode ImporterMod
 	// parse data content
 	dataRoot, err := xmlquery.Parse(strings.NewReader(content))
 	if err != nil {
-		return nil, errors.Wrapf(err, "failed to parse @TABLEAU string: %s", content)
+		return nil, errors.Wrapf(err, "failed to parse XML: %s", content)
 	}
 	for n := dataRoot.FirstChild; n != nil; n = n.NextSibling {
 		if n.Type != xmlquery.ElementNode {


Test patch:
diff --git a/internal/importer/xml_test.go b/internal/importer/xml_test.go
index 2031a6e..8fb40a9 100644
--- a/internal/importer/xml_test.go
+++ b/internal/importer/xml_test.go
@@ -1074,6 +1074,14 @@ func Test_splitRawXML(t *testing.T) {
 			wantContent: `<?xml version='1.0' encoding='UTF-8'?>
 
 
+
+
+
+
+
+
+
+
 <Server>
 	<Weight Num="1"/>
 	<Weight Num="2"/>
Repository: vaskoz/dailycodingproblem-go
Pull request #191 (2018-11-21 10:06:30)

day 90: encapsulate package variable into a type to enable parallelism
Associated with #189.


Patch:
diff --git a/day90/problem.go b/day90/problem.go
index fb6f868..e85940e 100644
--- a/day90/problem.go
+++ b/day90/problem.go
@@ -5,19 +5,19 @@ import (
 	"time"
 )
 
-var random *rand.Rand
+// Random encapsulates math/rand.Rand
+type Random struct {
+	random *rand.Rand
+}
 
-// getRandom returns a *math.Rand.
-func getRandom() *rand.Rand {
-	if random == nil {
-		random = rand.New(rand.NewSource(time.Now().UnixNano()))
-	}
-	return random
+// NewRandom returns a Random object.
+func NewRandom() *Random {
+	return &Random{rand.New(rand.NewSource(time.Now().UnixNano()))}
 }
 
 // RandMissingNumbers randomly generates a number from 0 to n-1 that isn't in l.
 // Runs in O(N) time and O(l) space.
-func RandMissingNumbers(n int, l []int) int {
+func (r *Random) RandMissingNumbers(n int, l []int) int {
 	m := make(map[int]struct{})
 	for _, v := range l {
 		m[v] = struct{}{}
@@ -26,7 +26,7 @@ func RandMissingNumbers(n int, l []int) int {
 	if size == 0 {
 		return -1
 	}
-	pos := getRandom().Intn(size)
+	pos := r.random.Intn(size)
 	val := -1
 	var i int
 	for i = 0; i < n; i++ {


Test patch:
diff --git a/day90/problem_test.go b/day90/problem_test.go
index fa1b131..1fa7a1a 100644
--- a/day90/problem_test.go
+++ b/day90/problem_test.go
@@ -14,12 +14,13 @@ var testcases = []struct {
 }
 
 func TestRandMissingNumbers(t *testing.T) {
-	//t.Parallel()//don't run in parallel
+	t.Parallel()
+	r := NewRandom()
 	for _, tc := range testcases {
 		results := make(map[int]int)
 		const iterations = 1000
 		for i := 0; i < iterations; i++ {
-			results[RandMissingNumbers(tc.n, tc.l)]++
+			results[r.RandMissingNumbers(tc.n, tc.l)]++
 		}
 		for _, v := range results {
 			delta := (float64(v) / float64(iterations)) - tc.distribution
@@ -34,16 +35,18 @@ func TestRandMissingNumbers(t *testing.T) {
 }
 
 func TestRandMissingNoNumbers(t *testing.T) {
-	//t.Parallel()//don't run in parallel
-	if result := RandMissingNumbers(5, []int{0, 1, 2, 3, 4}); result != -1 {
+	t.Parallel()
+	r := NewRandom()
+	if result := r.RandMissingNumbers(5, []int{0, 1, 2, 3, 4}); result != -1 {
 		t.Errorf("Expected -1 for a list that includes all possible numbers")
 	}
 }
 
 func BenchmarkRandMissingNumbers(b *testing.B) {
+	r := NewRandom()
 	for i := 0; i < b.N; i++ {
 		for _, tc := range testcases {
-			RandMissingNumbers(tc.n, tc.l)
+			r.RandMissingNumbers(tc.n, tc.l)
 		}
 	}
 }
Repository: vaskoz/dailycodingproblem-go
Pull request #603 (2019-06-13 22:52:53)

day 280: make it more deterministic
Specify a start node to help the algorithm operate deterministically.


Patch:
diff --git a/day280/problem.go b/day280/problem.go
index 6cb5540..e6ce38e 100644
--- a/day280/problem.go
+++ b/day280/problem.go
@@ -4,12 +4,7 @@ package day280
 type UndirectedGraph map[int]map[int]struct{}
 
 // HasCycle answers if the connected undirected graph is cyclic.
-func HasCycle(g UndirectedGraph) bool {
-	var start int
-	for node := range g {
-		start = node
-		break
-	}
+func HasCycle(g UndirectedGraph, start int) bool {
 	visits := make(map[int]bool)
 	return hasCycle(g, start, visits)
 }


Test patch:
diff --git a/day280/problem_test.go b/day280/problem_test.go
index a6feab0..203936c 100644
--- a/day280/problem_test.go
+++ b/day280/problem_test.go
@@ -5,6 +5,7 @@ import "testing"
 // nolint
 var testcases = []struct {
 	g      UndirectedGraph
+	start  int
 	cyclic bool
 }{
 	{
@@ -14,6 +15,7 @@ var testcases = []struct {
 			2: {0: struct{}{}},
 			3: {4: struct{}{}},
 		},
+		0,
 		true,
 	},
 	{
@@ -23,6 +25,7 @@ var testcases = []struct {
 			2: {3: struct{}{}},
 			3: {4: struct{}{}},
 		},
+		0,
 		false,
 	},
 }
@@ -30,7 +33,7 @@ var testcases = []struct {
 func TestHasCycle(t *testing.T) {
 	t.Parallel()
 	for _, tc := range testcases {
-		if cyclic := HasCycle(tc.g); cyclic != tc.cyclic {
+		if cyclic := HasCycle(tc.g, tc.start); cyclic != tc.cyclic {
 			t.Errorf("Expected %v, got %v", tc.cyclic, cyclic)
 		}
 	}
@@ -39,7 +42,7 @@ func TestHasCycle(t *testing.T) {
 func BenchmarkHasCycle(b *testing.B) {
 	for i := 0; i < b.N; i++ {
 		for _, tc := range testcases {
-			HasCycle(tc.g)
+			HasCycle(tc.g, tc.start)
 		}
 	}
 }