package Hash;
#
# A collection example for the algorithms class.
# See the docs at the end of this file.
#
use strict;
use warnings;
our $VERSION = '0.01';

require Exporter;
our @ISA = qw(Exporter);
our @EXPORT_OK = qw( ADD DELETE SEARCH FIRST NEXT COUNT RESET );

# --- package globals ----

# ADD, DELETE, SEARCH work on %hash.
our %hash;

# FIRST, NEXT work on @ordered, produced by sorting keys of %hash as needed.
our @ordered;
our $index;

# --- subroutines ---------

# Throw away info about ordered traversal.
sub reset_list {
  @ordered = ();
  $index = -1;
}

# Make sure the data can be traversed.
sub check_list {
  unless (@ordered){
    @ordered = sort {$a cmp $b} keys %hash;
    $index = 0;
  }
}

sub ADD {
  my ($word) = @_;
  $hash{$word} = 1;
  reset_list();
  return 1;
}

sub DELETE {
  my ($word) = @_;
  delete $hash{$word};
  reset_list();
  return 1;
}

sub SEARCH {
  my ($word) = @_;
  return exists $hash{$word};
}

sub FIRST {
  check_list();
  return NEXT();
}

sub NEXT {
  check_list();
  return $ordered[$index++];
}

sub COUNT {
  return scalar keys %hash;
}

sub RESET {
  %hash=();
  reset_list();
  return 1;
}

1;
__END__

=head1 NAME

Hash - example of an interface to a collection algorithm.

=head1 SYNOPSIS

  use Hash qw( ADD DELETE SEARCH FIRST NEXT );

  ADD $_ for qw( one two three four five );  # Put stuff into the collection
  DELETE('two');                             # Remove stuff.
  print "Found 'four'" if SEARCH 'four';     # Look for stuff.
  my $word = FIRST();                        # Loop over stuff.
  print "Here are the words: \n";
  while ($word){
    print $word, "\n";
    $word = NEXT();
  }

=head1 DESCRIPTION

One of several implementations of a collection algorithm.

=head1 SEE ALSO

List.pm, CollectionBenchmark.pm

=head1 AUTHOR

Jim Mahoney, E<lt>mahoney@maralboro.edu<gt>

=head1 COPYRIGHT AND LICENSE

Copyright 2005 by Jim Mahoney

This library is free software; you can redistribute it and/or modify
it under the same terms as Perl itself. 

=cut
