Skip to content

Instantly share code, notes, and snippets.

@naosim
Last active April 4, 2016 18:54
Show Gist options
  • Save naosim/c21ea4b697b63c8dc942 to your computer and use it in GitHub Desktop.
Save naosim/c21ea4b697b63c8dc942 to your computer and use it in GitHub Desktop.
javascriptでOptional
var Optional = (value) => {
var isNull = value === null || value === undefined;
return {
filter:(action) => (isNull || !action(value)) ? Optional() : Optional(value),
map:(action) => isNull ? Optional() : Optional(action(value)),
isPresent:() => !isNull,
ifPresent:(action) => {
if(!isNull) action(value);
},
get:() => isNull ? null : value,
orElse:(other) => isNull ? other : value,
orElseGet:(action) => isNull ? action() : value,
orElseThrow:(exceptionSupplier) => {
if(isNull) throw exceptionSupplier();
return value;
}
};
};
Optional.of = (value) => Optional(value);
Optional.empty = () => Optional();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment