Skip to content

Instantly share code, notes, and snippets.

@kirjavascript
Last active September 16, 2020 11:39
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kirjavascript/3c1f9ae47fa4a836f06b5408b9c394b3 to your computer and use it in GitHub Desktop.
Save kirjavascript/3c1f9ae47fa4a836f06b5408b9c394b3 to your computer and use it in GitHub Desktop.
MutString
<!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