Last active
April 4, 2016 18:54
-
-
Save naosim/c21ea4b697b63c8dc942 to your computer and use it in GitHub Desktop.
javascriptでOptional
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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