psl
psl copied to clipboard
feat(option): introduce option component
Signed-off-by: azjezz [email protected]
Pull Request Test Coverage Report for Build 3554950291
- 37 of 37 (100.0%) changed or added relevant lines in 3 files are covered.
- No unchanged relevant lines lost coverage.
- Overall coverage increased (+0.04%) to 98.977%
Totals | |
---|---|
Change from base Build 3554915568: | 0.04% |
Covered Lines: | 3386 |
Relevant Lines: | 3421 |
💛 - Coveralls
Just cross-linking here: I've provided a full example @ https://gist.github.com/Ocramius/368bd78c38cc5bb857e931801f6e4af7
Beware that Optional
is not necessarily OptionalField
.
-
Optional
in Java attempted to abstractT|null
(because Java sucks at handlingnull
- it's so so bad!). - in my example, I attempt to abstract
T|null|absent
, whereabsent
, which is a slightly different problem :+1:
forPossiblyMissingArrayKey
I was thinking with the addition of Option
, we could add the following functions to Dict
and Vec
components, which would implement basically that.
Dict\get<Tk, Tv>(dict<Tk, Tv> $d, Tk $k): Option<Tv> {
return Iter\contains_key($d, $k) ? Option\some($d[$k]) : Option\none();
}
Dict\get_typed<T>(dict<array-key, mixed> $d, array-key $k, Type\TypeInterface<T> $t): Option<T> {
return Iter\contains_key($d, $k) ? Option\some($t->coerce($d[$k])) : Option\none();
}
Vec\get<T>(vec<T> $v, int $k): Option<T> {
return Iter\contains_key($v, $k) ? Option\some($v[$k]) : Option\none();
}
Vec\get_typed<T>(vec<mixed> $v, int $k, Type\TypeInterface<T> $t): Option<T> {
return Iter\contains_key($v, $k) ? Option\some($t->coerce($v[$k])) : Option\none();
}
in my example, I attempt to abstract T|null|absent, where absent, which is a slightly different problem 👍
To note, null
is a valid "Some" in this implementation of Option, where Option\some(null)->isNone()
is false
, it's up to you to create a "none" in case of null if that is what you desire.
Discussed the open topics in this PR with @azjezz. There is nothing blocking that is stopping us from merging and releasing this PR. We can always take in additional improvements once people start using this component and start seeing better ways to do things.