Data-Queue

 view release on metacpan or  search on metacpan

lib/Data/Queue.pm  view on Meta::CPAN

package Data::Queue;

=head1 NAME

Data::Queue - Order/Unordered stack

=head1 SYNOPSIS

  use Data::Queue;

  my $stack=new Data::Queue;

  my $id=$stack->add($job);

  while($stack->has_next) {
    my ($id,$job)=$stack->get_next;
  }

=head1 DESCRIPTION

Stack, with the ablity to add and remove elements by id on the fly. Elements go in and out of the stack in the id order.

=cut

use Modern::Perl;
use Moo;
use Data::Result;
use namespace::clean;
our $VERSION='1.0002';

with 'Data::Result::Moo';

sub BUILD {
  my ($self,$args)=@_;
  my $data={};
  $self->{id}=0;
  $self->{data}={};
  $self->{stack}=[];
};

=head1 OO Methods

=over 4

=item * my @ids=$stack->add(@list)

Adds a list of objects onto the stack

Arguments:

  @ids:  List of ids relative to @list
  @list: List of elements to put on the stack

=cut

sub add {
  my ($self,@list)=@_;

  my @result;
  my $list=$self->{list};
  foreach my $obj (@list) {
    $self->{id}++;
    my $set=[$self->{id},$obj];

    $self->{data}->{$self->{id}}=$set;
    push @{$self->{stack}},$self->{id};
    push @result,$self->{id};
  }

  @result;
}

=item * my ($id,$value)=$stack->get_next

Returns the next id=>value pair from the set.

=cut

sub get_next {
  my ($self)=@_;
  my $id=shift @{$self->{stack}};
  my $set=delete $self->{data}->{$id};

  return wantarray ? @{$set} : $set->[1];
}



( run in 0.618 second using v1.01-cache-2.11-cpan-437f7b0c052 )