Skip to content

Instantly share code, notes, and snippets.

@LFSaw
Last active August 29, 2015 14:09
Show Gist options
  • Save LFSaw/e0a915069387073a0976 to your computer and use it in GitHub Desktop.
Save LFSaw/e0a915069387073a0976 to your computer and use it in GitHub Desktop.
towards Dictionary:inject
Associations : List {
pairsDo { |func|
this.do { |assoc|
func.value(assoc.key, assoc.value)
}
}
keysValuesDo { |func|
this.pairsDo(func)
}
keys {
^this.collect { |assoc| assoc.key }
}
values {
^this.collect { |assoc| assoc.value }
}
includes { arg value;
this.do { arg assoc; if (assoc.value == value) { ^true } };
^false
}
includesKey { arg key;
this.do { arg assoc; if (assoc.key == key) { ^true } };
^false
}
asAssociations {
^this
}
asPairs {
var res = Array.new(this.size * 2);
this.do { |assoc| res.add(assoc.key).add(assoc.value) }
^res
}
}
+ Collection {
hasAssociations {
// now obviously, this is disputable.
// the alternative is to make an explicit class that decides this.
// on the other hand: does this outweigh the exclusion of associaotions as keys for associations?
^this.at(0).isKindOf(Association)
}
asAssociations {
var res;
if(this.hasAssociations) { ^this };
res = Array.new(this.size div: 2);
this.pairsDo { |key, val| res.add(key -> val) }
^res
}
asPairs {
var res;
if(this.hasAssociations.not) { ^this };
res = Array.new(this.size div: 2);
this.do { |assoc| res.add(assoc.key).add(assoc.value) }
^res
}
asDict { |mergeFunc|
var res = IdentityDictionary.new; // another dispute: Dictionary would default to a very inefficient lookup.
if(mergeFunc.notNil) { ^this.asDictWith(mergeFunc) };
if(this.hasAssociations) {
this.do { |assoc|
res.put(assoc.key, assoc.value)
}
} {
this.pairsDo { |key, val|
res.put(key, val)
}
};
^res
}
asDictWith { |mergeFunc|
var res = IdentityDictionary.new;
if(this.hasAssociations) {
this.do { |assoc|
res.mergeItem(assoc.key, assoc.value, mergeFunc)
}
} {
this.pairsDo { |key, val|
res.mergeItem(key, val, mergeFunc)
}
};
^res
}
}
+ SequenceableCollection {
hasAssociations {
^this.subclassResponsibility(thisMethod)
}
}
+ Dictionary {
hasAssociations { ^false }
asPairs {
^this.getPairs
}
asDict {
^this
}
mergeItem { |key, val, func|
var old;
if(func.notNil) {
old = this.at(key);
if(old.notNil) {
val = func.value(val, old)
}
};
this.put(key, val)
}
}
(
(\a: 1, \b: 2).asAssociations.inject([], {|last, item|
last ++ [[item.key, item.value]]
})
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment