While working with MochiKit I've accumulated a bunch of helper methods.
It's possible that there is already a better way to do some of these
things, which I'd be grateful to learn. Anyway, feel free to adopt or
improve them if they seem useful.

1) I discovered that if you Base.clone an object then try to delete a
property it doesn't work as expected (the copy-on-write magic of clone
makes this impossible). Here is an eagerly copying version, which uses
a subset helper method which is useful in its own right:

function eagerClone(obj) {
  return subset(obj, MochiKit.Base.keys(obj));
}

function subset(obj, keys) {
  var copy = {};
  for (var i in keys) {
    var key = keys[i];
    copy[key] = obj[key];
  }
  return copy;
}

2) I use Base.keys all the time, so the lack of a values method was
surprising:

function values(obj) {
  return MochiKit.Base.map(function(x) { return obj[x] },
MochiKit.Base.keys(obj));
}

3) Similarly, a way to reverse the effect of Base.items is useful. With
it you can write methods to "map" just the values of an object:

function objectFromItems(items) {
  var obj = {};
  for (var i in items) {
    var item = items[i];
    obj[item[0]] = item[1];
  }
  return obj;
}

function mapItems(fn, obj) {
  return objectFromItems(MochiKit.Base.map(fn,
MochiKit.Base.items(obj)));
}

function mapValues(fn, obj) {
  return mapItems(function(item) {
    return [item[0], fn(item[1], item[0])];
  }, object);
}

4) This one is a little more random--rotating an array in either
direction:

function rotateArray(array, amount) {
  if (amount > 0)
    pushAll(array, array.splice(0, amount));
  else if (amount < 0)
    unshiftAll(array, array.splice(array.length + amount, -amount));
}

function pushAll(dest, array) {
  Array.prototype.push.apply(dest, array);
}

function unshiftAll(dest, array) {
  Array.prototype.unshift.apply(dest, array);
}

Thanks,
Chris


--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups 
"MochiKit" group.
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at http://groups.google.com/group/mochikit
-~----------~----~----~----~------~----~------~--~---

Reply via email to