Skip to content

Instantly share code, notes, and snippets.

@WebReflection
Last active April 19, 2018 06:34
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save WebReflection/7059536 to your computer and use it in GitHub Desktop.
Save WebReflection/7059536 to your computer and use it in GitHub Desktop.
After a discussion on symbols VS code points VS strings in es-discuss … here some outcome
!function(dict, from){
/**
* DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
* Version 2, December 2004
*
* Copyright (C) 2004 Sam Hocevar <sam@hocevar.net>
*
* Everyone is permitted to copy and distribute verbatim or modified
* copies of this license document, and changing it is allowed as long
* as the name is changed.
*
* DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
* TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
*
* 0. You just DO WHAT THE FUCK YOU WANT TO.
*/
function getOrCreate(str) {
if (!(str in dict)) {
dict[str] = {
i: 0,
l: 0,
v: from(str)
};
}
// times it's used
dict[str].i++;
return dict[str].v;
}
setInterval(function () {
var key, value;
for(key in dict) {
value = dict[key];
value.l = value.i - value.l;
// used only once or never used again
if (value.l < 2) {
// free all the RAM
delete dict[key];
}
}
}, 5000); // 5 seconds should be enough ?
// incremental works better with
// slower timeout though
// 500 might be good too
Object.defineProperties(
String.prototype,
{
at: {
configurable: true,
writable: true,
value: function at(i) {
return getOrCreate(this)[i];
}
},
// or any meaningful name
size: {
configurable: true,
get: function () {
return getOrCreate(this).length;
}
}
}
);
}(
Object.create(null),
Array.from || function (str) {
// miserable fallback
// or the for/of loop
// just as example in here
return str.split('');
}
);
/* @example
var str = 'a💩c'; // in ES6 or where supported
var str = 'abc'; // today
alert([
str.size, // 3
str.at(1), // b or 💩 in ES6
str.at(2) // c
]);
*/
@WebReflection
Copy link
Author

preemptive answer: why not just a WeakMap ?

When a primitive string invokes a method or is passed as context it's automatically wrapped into an Object so every time you invoke that method the string will be wrapped by a different object.

Accordingly, the WeakMap would create as many strings as invocations making the whole code pointless.

var str = 'abc', last;
String.prototype.method = function () {
  if (this.done) alert('never');
  this.done = true;
  if(last == this) alert('never');
  last = this;
};
str.method();
str.method();
str.method();

Thanks for asking or reading this.

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