Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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

This comment has been minimized.

Copy link
Owner Author

@WebReflection WebReflection commented Oct 19, 2013

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