Last active
September 16, 2020 11:39
-
-
Save kirjavascript/3c1f9ae47fa4a836f06b5408b9c394b3 to your computer and use it in GitHub Desktop.
MutString
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
<!DOCTYPE html> | |
<html lang="en"> | |
<head> | |
<meta charset="UTF-8" /> | |
<meta name="viewport" content="width=device-width, initial-scale=1.0" /> | |
<meta http-equiv="X-UA-Compatible" content="ie=edge" /> | |
<title>Static Template</title> | |
</head> | |
<body> | |
<script> | |
const mutString = new MutString("test"); | |
mutString[2] = "x"; | |
document.body.textContent = ` | |
${mutString[2]} | |
${mutString} | |
${mutString.match(/^../)} | |
${mutString.bold()} | |
${mutString.length} | |
`; | |
function MutString(str) { | |
const list = [...str]; | |
return new Proxy( | |
{}, | |
{ | |
get(target, key, recv) { | |
if (key === Symbol.toPrimitive) { | |
return () => list.join(""); | |
} | |
if (typeof String.prototype[key] === "function") { | |
return String.prototype[key].bind(list.join("")); | |
} | |
if (1 / key) { | |
return list[key]; | |
} | |
if (key === "length") { | |
return list.length; | |
} | |
return Reflect.get(new String(list.join("")), key, recv); | |
}, | |
set(target, key, value) { | |
list.splice(key, 1, ...String(value)); | |
list.splice(0, list.length, ...list.filter(ch => ch)); | |
} | |
} | |
); | |
} | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment