Skip to content

Instantly share code, notes, and snippets.

@Dobby233Liu
Created August 8, 2020 04:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Dobby233Liu/878e2ce2dc0eb60b63a4d1b8d313c37b to your computer and use it in GitHub Desktop.
Save Dobby233Liu/878e2ce2dc0eb60b63a4d1b8d313c37b to your computer and use it in GitHub Desktop.
function generateStringByTemplate(arr){
// FIXME: This is a temporary solution. It may cause overflows.
// If you have an excellent way to do this, tell me.
main = ""
for (i of arr) {
z = ""
if (typeof i != "string") { // is i not a string?
if (Array.isArray(i))
z = i // assign a placeholder
else
throw new TypeError("indexed element is neither a string nor an array, got a(n) " + typeof i + "instead")
while (Array.isArray(z)) { // if z is (still) a array, index to the end using a while loop (FIXME)
z = z[Math.floor(Math.random() * z.length)] // get another (replacement) element
if (typeof z != "string" && !Array.isArray(z)) // do it have a vaild type?
throw new TypeError("randomly selected element in array z is neither a string nor an array, got a(n) " + typeof i + "instead")
}
}
else
z = i // just assign it to z
main += z
}
return main
}
@Dobby233Liu
Copy link
Author

generateStringByTemplate([
	["Don't worry. ", ""],
	[["She","Her mom"],["He", "His dad"]], " ",
	["can", ["might", "may"], ["must", "have to"], "will"], " ",
	["call", ["call by phone to", "phone"]], " ",
	["you", "Jane", "John", ["Lily", "Lily's dad"]], "",
	[[" for it.", " for more info."], "."]
])

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment