Skip to content

Instantly share code, notes, and snippets.

@nicomen
Last active June 21, 2016 12:51
Show Gist options
  • Save nicomen/318ef68a6d165a88572e660c232fa3ed to your computer and use it in GitHub Desktop.
Save nicomen/318ef68a6d165a88572e660c232fa3ed to your computer and use it in GitHub Desktop.
#!/usr/bin/perl -l
use strict;
use warnings;
use Mojo::Util;
use Mojo::Collection;
Mojo::Util::monkey_patch('Mojo::Collection', sort_by_attr_order => sub {
my ($self, $attr, $order) = @_;
my %order_map = map { $order->[$_] => $_ } 0..@{$order}-1;
return $self->sort( sub { $order_map{$a->{$attr}} <=> $order_map{$b->{$attr}} } );
});
print Mojo::Collection->new ( { a => 2 }, { a => 1 }, { a =>3 } )
->sort_by_attr_order( a => [ 3, 2, 1 ] )
->map ( sub { $_->{a} } )
->join ( ', ' );
# 3, 2, 1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment