Skip to content

Commit 25b4ab1

Browse files
committed
Revert "Merge pull request #6 from MartinFiorde/refactor/clean-personal-practice"
This reverts commit 2430990, reversing changes made to b768f15.
1 parent 2430990 commit 25b4ab1

File tree

22 files changed

+767
-30
lines changed

22 files changed

+767
-30
lines changed

docs/Apuntes java functional.docx

644 KB
Binary file not shown.

docs/Functional SE.pdf

1.12 MB
Binary file not shown.
312 KB
Loading

jobs-search-reporter/src/main/java/com/platzi/jobsearch/CommanderFunctions.java

Lines changed: 22 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,20 @@
88
import java.util.function.Supplier;
99

1010
public interface CommanderFunctions {
11+
/**
12+
* JCommander permite generar opciones de terminal de cualquier clase, por eso el primer parametro es
13+
* de tipo Object.
14+
*
15+
* @param object Clase de la cual se generaran los argumentos de JCommander
16+
* @return una instancia de JCommander. Idealmente con CLIArguments como objeto pasado.
17+
*/
18+
static JCommander buildCommander(Object object) {
19+
return JCommander
20+
.newBuilder()
21+
.addObject(object)
22+
.build();
23+
}
24+
1125
/**
1226
* Con esta funcion, facilitamos crear una configuracion inicial de JCommander, pidiendo el nombre del
1327
* programa y un Supplier de tipo T para los argumentos. Asi podemos usar alguna funcion que nos devuelva
@@ -19,11 +33,7 @@ public interface CommanderFunctions {
1933
* @return una instancia de {@link JCommander} ya configurada con el nombre y los argumentos.
2034
*/
2135
static <T> JCommander buildCommanderWithName(String name, Supplier<T> argumentsSupplier) {
22-
// JCommander permite generar opciones de terminal de cualquier clase, por eso se le agrega un object con el metodo addObject(...)
23-
// argumentsSupplier.get() es la clase de la cual se generaran los argumentos de JCommander
24-
// Queda definida una instancia de JCommander. Idealmente con CLIArguments como objeto pasado.
25-
JCommander jCommander = JCommander.newBuilder().addObject(argumentsSupplier.get()).build();
26-
36+
JCommander jCommander = buildCommander(argumentsSupplier.get());
2737
jCommander.setProgramName(name);
2838
return jCommander;
2939
}
@@ -35,14 +45,18 @@ static <T> JCommander buildCommanderWithName(String name, Supplier<T> argumentsS
3545
static Optional<List<Object>> parseArguments(
3646
JCommander jCommander,
3747
String[] arguments,
38-
OnCommandError onCommandError) { // en caso que las validaciones de CLIKeywordValidaror o CLIHelpValidator fallen, se generará un ParameterException
48+
OnCommandError onCommandError
49+
) {
50+
List<Object> result;
3951
try {
4052
jCommander.parse(arguments);
53+
4154
return Optional.of(jCommander.getObjects());
42-
} catch (ParameterException exception) { // atrapará el parameter exception y devuelve un optional vacio
55+
} catch (ParameterException exception) {
4356
onCommandError.onError(jCommander);
44-
return Optional.empty();
4557
}
58+
59+
return Optional.empty();
4660
}
4761

4862
@FunctionalInterface

jobs-search-reporter/src/main/java/com/platzi/jobsearch/JobSearch.java

Lines changed: 16 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -21,22 +21,31 @@ public static void main(String[] args) {
2121
JCommander jCommander = buildCommanderWithName("job-search", CLIArguments::newInstance);
2222

2323
//Obtenemos las opciones que se le dieron a JCommander
24-
Stream<CLIArguments> streamOfCLI = parseArguments(jCommander, args, JCommander::usage) //Nos retorna un Optional<List<Object>>
25-
.orElse(Collections.emptyList()) //En caso de un Optional.empty()
24+
Stream<CLIArguments> streamOfCLI =
25+
//Nos retorna un Optional<List<Object>>
26+
parseArguments(jCommander, args, JCommander::usage)
27+
//En caso de un Optional.empty()
28+
.orElse(Collections.emptyList())
2629
.stream()
2730
.map(CLIArguments.class::cast); // map(obj -> (CLIArguments) obj) give same result
2831

2932
//Tomamos nuestro Stream y obtenemos las opciones que se dieron en el CLI
3033
Optional<CLIArguments> cliOptional = streamOfCLI
31-
.filter(cli -> !cli.isHelp()) //Solo nos interesan los casos donde no sea la solicitud de ayuda
32-
.filter(cli -> cli.getKeyword() != null) //Y que contengan un keyword, en otros caso no tenemos que buscar
34+
//Solo nos interesan los casos donde no sea la solicitud de ayuda
35+
.filter(cli -> !cli.isHelp())
36+
//Y que contengan un keyword, en otros caso no tenemos que buscar
37+
.filter(cli -> cli.getKeyword() != null)
3338
.findFirst();
3439

3540
//Si el Optional tiene un dato, lo convertimos a Map<String,Object>
3641
cliOptional.map(CLIFunctions::toMap)
37-
.map(JobSearch::executeRequest) //Convertimos el Map en un request
38-
.orElse(Stream.empty()) //Aun seguimos operando sobre un Optional… en caso de que no hubiera datos generamos un stream vacio
39-
.forEach(System.out::println); //Imprimos los datos por pantalla.
42+
//Convertimos el Map en un request
43+
.map(JobSearch::executeRequest)
44+
//Aun seguimos operando sobre un Optional… en caso de que no hubiera datos
45+
//Generamos un stream vacio
46+
.orElse(Stream.empty())
47+
//Imprimos los datos por pantalla.
48+
.forEach(System.out::println);
4049
}
4150

4251
private static Stream<JobPosition> executeRequest(Map<String, Object> options) {

jobs-search-reporter/src/main/java/com/platzi/jobsearch/cli/CLIArguments.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -44,7 +44,7 @@ public final class CLIArguments {
4444
private boolean isMarkdown = false;
4545

4646
@Parameter(
47-
names = {"--help", "-h"},
47+
names = "--help",
4848
help = true,
4949
validateWith = CLIHelpValidator.class,
5050
description = "Muestra esta ayuda")

jobs-search-reporter/src/main/java/com/platzi/jobsearch/cli/CLIKeywordValidator.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@
1111
public class CLIKeywordValidator implements IParameterValidator {
1212
@Override
1313
public void validate(String name, String value) throws ParameterException {
14-
if (!value.matches("^[a-zA-Z]+\\d*$")) {
14+
if (!value.matches("^[a-zA-Z]+[0-9]*$")) {
1515
System.err.println("Keyword: " + value + " no es un Keyword valido, keywords deben ser alfanumericas.\n");
1616
throw new ParameterException("Only alphanumerics are supported");
1717
}
Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,66 @@
11
package com.platzi.functional_student_practice._03_inmutable;
22

3+
import java.util.List;
4+
35
public class C8InmutObjWithMutAttributes {
6+
7+
public static void main(String[] args) {
8+
9+
System.out.println("////////////////////////////////////////////////////////////////////////////////////");
10+
System.out.println("\nCLASS 8\n");
11+
12+
// 1. We make an inmutable object (without setters)
13+
Direccion dir = new Direccion("New York");
14+
15+
// 2. We make a mutable object (with setters)
16+
Persona p1 = new Persona(dir);
17+
18+
// 3. We make an inmutable list
19+
List<Persona> lista1 = List.of(p1);
20+
21+
// 4. Try to change mutable element from inmutable list is allowed
22+
System.out.println("Antes de modificar: " + lista1);
23+
p1.getDireccion().setCiudad("Los Angeles");
24+
System.out.println("Después de modificar: " + lista1);
25+
26+
}
27+
28+
private static class Direccion {
29+
String ciudad;
30+
31+
Direccion(String ciudad) {
32+
this.ciudad = ciudad;
33+
}
34+
35+
String getCiudad() {
36+
return ciudad;
37+
}
38+
39+
void setCiudad(String ciudad) {
40+
this.ciudad = ciudad;
41+
}
42+
43+
@Override
44+
public String toString() {
45+
return ciudad;
46+
}
47+
}
48+
49+
private static class Persona {
50+
private final Direccion direccion;
51+
52+
Persona(Direccion direccion) {
53+
this.direccion = direccion;
54+
}
55+
56+
public Direccion getDireccion() {
57+
return direccion;
58+
}
59+
60+
@Override
61+
public String toString() {
62+
return "Persona{direccion=" + direccion + "}";
63+
}
64+
}
65+
466
}
Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,74 @@
11
package com.platzi.functional_student_practice._04_functional;
22

3+
import java.util.function.IntPredicate;
4+
import java.util.function.IntUnaryOperator;
5+
import java.util.function.Predicate;
6+
37
public class C11y12MathFunctions {
8+
public static void main(String[] args) {
9+
10+
System.out.println("////////////////////////////////////////////////////////////////////////////////////");
11+
System.out.println("\nCLASS 11\n");
12+
13+
// 1. function as type
14+
// Function<Integer, Integer> square1 = new Function<Integer, Integer>() {
15+
// @Override
16+
// public Integer apply(Integer x) {
17+
// return x * x;
18+
// }
19+
// };
20+
// System.out.println(square1.apply(5)+"\n");
21+
22+
// 2. function 1 writen in a more performant way
23+
IntUnaryOperator square2 = x -> x * x;
24+
System.out.println(square2.applyAsInt(6)+"\n");
25+
26+
// 3. function 3 declared in the class, outside the main method
27+
System.out.println(square3(7));
28+
System.out.println(square3(8)+"\n");
29+
30+
31+
System.out.println("////////////////////////////////////////////////////////////////////////////////////");
32+
System.out.println("\nCLASS 12\n");
33+
34+
// 1. Function as type using lambda to declare operation in one line
35+
// Function<Integer, Boolean> isOdd1 = x -> x % 2 == 1;
36+
// System.out.println(isOdd1.apply(7));
37+
// System.out.println(isOdd1.apply(8)+"\n");
38+
39+
// 2. function 1 writen in a more performant way
40+
IntPredicate isOdd2 = x -> x % 2 == 1;
41+
System.out.println(isOdd2.test(7));
42+
System.out.println(isOdd2.test(8)+"\n");
43+
44+
// 3. function Predicate by teacher
45+
// Predicate<Integer> isEven1 = x -> x % 2 == 0;
46+
// System.out.println(isEven1.test(7));
47+
// System.out.println(isEven1.test(8)+"\n");
48+
49+
// 4. function 3 performant
50+
IntPredicate isEven2 = x -> x % 2 == 0;
51+
System.out.println(isEven2.test(7));
52+
System.out.println(isEven2.test(8)+"\n");
53+
54+
// 5. Student example
55+
Predicate<Student> isApproved = student -> student.getQualification()>= 7;
56+
System.out.println(isApproved.test(new Student(6)));
57+
System.out.println(isApproved.test(new Student(7)));
58+
}
59+
60+
private static int square3(int x) {
61+
return x * x;
62+
}
63+
64+
private static class Student {
65+
private final double qualification;
66+
public Student(double qualification) {
67+
this.qualification = qualification;
68+
}
69+
public double getQualification() {
70+
return qualification;
71+
}
72+
}
73+
474
}
Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,57 @@
11
package com.platzi.functional_student_practice._04_functional;
22

3+
import java.util.ArrayList;
4+
import java.util.List;
5+
import java.util.function.Consumer;
6+
import java.util.function.Supplier;
7+
38
public class C13CLIUtils {
9+
10+
public static void main(String[] args) {
11+
12+
System.out.println("////////////////////////////////////////////////////////////////////////////////////\n");
13+
System.out.println("CLASS 13\n");
14+
15+
// 1. Created CLI class, consumer and supplier
16+
List<CLIArguments> list = new ArrayList<>();
17+
for (int i = 0; i < 5; i++) {
18+
list.add(generateCLI());
19+
list.get(i).setHelp(i % 2 == 0);
20+
}
21+
22+
for (int i = 0; i < list.size(); i++) {
23+
showHelp(list.get(i), i);
24+
}
25+
26+
}
27+
28+
29+
private static void showHelp(CLIArguments cliArguments, int i) {
30+
Consumer<CLIArguments> consumerHelper = cliArguments1 -> {
31+
if (cliArguments1.isHelp()) {
32+
System.out.println(i +": Manual required");
33+
}
34+
};
35+
consumerHelper.accept(cliArguments);
36+
}
37+
38+
39+
private static CLIArguments generateCLI() {
40+
Supplier<CLIArguments> generator = CLIArguments::new; //same as () -> new CLIArguments()
41+
return generator.get();
42+
}
43+
44+
45+
private static class CLIArguments {
46+
private boolean isHelp;
47+
48+
public boolean isHelp() {
49+
return isHelp;
50+
}
51+
52+
public void setHelp(boolean help) {
53+
isHelp = help;
54+
}
55+
}
56+
457
}

0 commit comments

Comments
 (0)