Last active
December 22, 2015 17:18
-
-
Save leesei/6504908 to your computer and use it in GitHub Desktop.
#js #snippet #prompt2 Generic function that extends `window.prompt()`.
This file contains 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
/** | |
`result = prompt2([prompt , options|default]);` | |
Generic function that extends `window.prompt()`. | |
If `options.validate()` is provided, this function will loop until the function return true on user's input. | |
Empty string (`''`) will be used instead of passing `undefined` for `prompt` and `default`. | |
If an non-Object is passed for options, it will be used as default value | |
(compatible with `window.prompt()`, no validation is performed). Use | |
`options.defaultValue` to pass an Object as default value. | |
*Arguments*: | |
# `prompt` (String): The text to display to the user | |
# `options` (Object): Option object with the following properties: | |
`defaultValue`: User specified default value | |
`validate` (Function): The function called to validate result | |
# `default` (non Object): User specified default value | |
*/ | |
function prompt2(prompt, options) { | |
var promptString = (prompt !== 'undefined')? prompt:''; | |
var defaultValue = ''; | |
var opts = {}; | |
if (typeof options !== 'undefined') { | |
if (typeof options === 'object') { | |
opts = options; | |
} | |
else { | |
defaultValue = options; | |
} | |
} | |
// default validate(), no-op | |
var validate = function (result) { | |
return true; | |
}; | |
if (typeof opts.defaultValue !== 'undefined') { | |
defaultValue = opts.defaultValue; | |
} | |
if (typeof opts.validate === 'function') { | |
validate = opts.validate; | |
} | |
var result = null; | |
do { | |
// do-while is better then while-break here | |
result = window.prompt(promptString, defaultValue); | |
} while (!validate(result)); | |
return result; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment