Created
January 3, 2023 15:25
-
-
Save thiagosperandio/5f37159b383ed0290a9bfa3d7ce0310b to your computer and use it in GitHub Desktop.
function makePhrase.js.html
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
<script language="JavaScript"> | |
function isArrayOrObject(val) { | |
return val instanceof Array || val instanceof Object; | |
} | |
function isStringOrWrapper(val) { | |
return typeof val === 'string' || val instanceof String; | |
} | |
/** | |
* If obj arg is a array after evaluation, returns the strPlural arg, otherwise returns strSingle arg. | |
* | |
* Evaluates checking: | |
* - if obj arg is undefined, null, empty string, or only one element, or is not a array or an object. | |
* - apply split function, if strToSplit arg is present | |
* */ | |
function makePhrase(obj, strSingle, strPlural, strToSplit) { | |
if (!obj?.length || obj.length === 1) { | |
return strSingle; | |
} else if (isArrayOrObject(obj) && obj.length > 1) { | |
return strPlural; | |
} else if (isStringOrWrapper(obj) && !!strToSplit && obj.split(strToSplit)?.length > 1) { | |
return strPlural; | |
} else { | |
return strSingle; | |
} | |
} | |
/*--- TESTS: -------------------------------------------------------------*/ | |
function isJSONStr(str) { | |
try { | |
return (JSON.parse(str) && !!str); | |
} catch (e) { | |
return false; | |
} | |
} | |
/** | |
* Testado com: | |
* - [{"aField": 1}, {"aField": 2}] | |
* - [{"aField": 1}] | |
* - {"aField": 1} | |
* - vazio | |
* - null | |
* - [1,2,3] | |
* - strings quaisquer com e sem espaço | |
* - strings quaisquer com algum split a ser feito | |
*/ | |
let testValue = window.prompt("informe um objeto para teste: ", '[{"aField": 1}, {"aField": 2}]'); | |
let strToSplit = window.prompt("informe a string para o split: ", ""); | |
if (isJSONStr(testValue)) { | |
testValue = JSON.parse(testValue); | |
} | |
window.alert(makePhrase(testValue, "single phrase!", "plural phrase!", strToSplit)); | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment