Skip to content

Instantly share code, notes, and snippets.

@mgandin
Last active November 5, 2015 09:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save mgandin/e56f811c613be121233c to your computer and use it in GitHub Desktop.
Save mgandin/e56f811c613be121233c to your computer and use it in GitHub Desktop.
Functional FooBarQix ...
package fr.mga.functional;
import java.util.HashMap;
import java.util.Map;
import static java.lang.Character.getNumericValue;
import static java.util.stream.Collectors.joining;
public class FooBar {
public String imperative(int numberToFoobar) {
String result = "";
if(numberToFoobar % 3 == 0) {
result += "FOO";
}
if(numberToFoobar % 5 == 0) {
result += "BAR";
}
if(numberToFoobar % 7 == 0) {
result += "QIX";
}
String toFooBar = String.valueOf(numberToFoobar);
for (int j = 0; j < toFooBar.length(); j++) {
char element = toFooBar.charAt(j);
if(element == '3')
result += "FOO";
if(element == '5')
result += "BAR";
if(element == '7')
result += "QIX";
}
return result.isEmpty() ? toFooBar : result;
}
public String func(int numberToFooBar) {
Map<Integer, String> foobar = fooBarQix();
String result = contains(numberToFooBar, foobar);
String toFooBar = String.valueOf(numberToFooBar);
result += contains(foobar, toFooBar);
return result.isEmpty() ? toFooBar : result;
}
private String contains(Map<Integer, String> foobar, String toFooBar) {
return toFooBar.chars()
.mapToObj(integerAsChar -> foobar.getOrDefault(getNumericValue(integerAsChar), ""))
.collect(joining());
}
private String contains(int numberToFooBar, Map<Integer, String> foobar) {
return foobar.keySet().stream()
.filter(toReplace -> numberToFooBar % toReplace == 0)
.map(foobar::get)
.collect(joining());
}
private Map<Integer, String> fooBarQix() {
Map<Integer, String> foobar = new HashMap<>();
foobar.put(3, "FOO");
foobar.put(5, "BAR");
foobar.put(7, "QIX");
return foobar;
}
}
package fr.mga.functional;
import org.fest.assertions.api.Assertions;
import org.junit.Test;
public class FooBarTest {
@Test
public void should_make_the_foobar() {
FooBar fooBar = new FooBar();
for (int i = 1; i < 101; i++) {
System.out.println(fooBar.func(i));
Assertions.assertThat(fooBar.func(i)).isEqualTo(fooBar.imperative(i));
}
}
}
@vandekeiser
Copy link

@mgandin
Copy link
Author

mgandin commented Mar 12, 2015

Bien vu, j'ai repris quelques modifs !

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment