Skip to content

Instantly share code, notes, and snippets.

@Garciat
Last active December 15, 2015 12:39
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 Garciat/5261758 to your computer and use it in GitHub Desktop.
Save Garciat/5261758 to your computer and use it in GitHub Desktop.
function list(v) {
function errchk(f, e) {
try {
return f();
} catch (err) {
if (err instanceof ReferenceError &&
err.message.match(/^[v]+\s/) !== null) {
return e ? e() : undefined;
}
throw err;
}
}
var fn = {
add: function (val) {
return eval('(' + list.toString()
.replace(/\(([v]+)\)/, '($1v)') + ')')(val);
},
get: function (i) {
if (i < 0) {
throw new RangeError();
}
return errchk(function () {
return eval(Array(i + 2).join('v'));
}, function () {
throw new RangeError();
});
},
set: function (i, val) {
this.get(i);
eval(Array(i + 2).join('v') + ' = val');
},
each: function (f) {
errchk(function () {
for (var vs = 'v';; vs += 'v') {
f(eval(vs));
}
});
},
to_a: function () {
var a = [];
this.each(a.push.bind(a));
return a;
}
};
Object.keys(fn).forEach(function (k) {
fn[k] = fn[k].bind(fn);
});
return fn;
}
// uso / usage:
var l1 = list('hola');
var l2 = l1.add('como').add('estas');
l1 = l1.add('javier');
l2.set(0, 'hello'); // === l1.set(0, 'hello')
console.log(l1.to_a().join(' '));
console.log(l2.to_a().join(' '));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment