Create an object/Native demonstration

From Rosetta Code
Revision as of 22:01, 15 February 2011 by rosettacode>Kernigh (→‎{{header|Ruby}}: Add some important parts (lFencedHash#delete, FencedHash#store).)
Create an object/Native demonstration is a draft programming task. It is not yet considered ready to be promoted as a complete task, for reasons that should be found in its talk page.

Task:

Create a Hash/Associative Array/Dictionary-like object, which is initialized with some default key/value pairs. The object should behave like a native Hash/Associative Array/Dictionary of the language, if any, but with the following differences:

  1. No new item can be added;
  2. Item cannot be deleted, (but native delete method may used to reset the item's value to default) ;

Objective:

The objective is not just create such object, but to demonstarion the language's native way of object creation. For some language, the task should show how the so-called Magic Methods work.

J

Given a list of keys and an associated list of values, the idiomatic way of expressing this concept in J would be:

<lang j>lookup=: values {~ keys&i.</lang>

For example:

<lang j> lookup=: 10 20 30 40 50 {~ (;:'this is a test')&i.

  lookup ;:'a test'

30 40</lang>

Notes:

1) While the result can not be modified or deleted, the name used to refer to it can be made to refer to something else, and once all references are lost it will be garbage collected.

2) In the above example, we have 5 values and 4 keys. The extra value is used when no key is found. If no extra value was provided, the "key not found" case would be an error case.

3) In J, objects are always referenced, but all data is passed by value. This means that objects can never be passed to a function -- only a reference to an object (its name) can be passed. This means that objects exist only in the way things are named, in J. So for the most part, we do not call things "objects" in J, and this task has nothing to do with what are called "objects" in J. However, this does demonstrate how things are created in J -- you write their definition, and can use them and/or assign to names or inspect them or whatever else.

JavaScript

This is a first demonstration of the task, but only implemented the functionality, not any native behavior, eg indexing. JavaScript experts may want to replace this one.

Works with: JavaScript version 1.7

<lang javascript>var keyError = new Error("Invalid Key Error (FixedKeyDict)") ;

function FixedKeyDict(obj) {

   var myDefault = new Object() ;
   var myData    = new Object() ;
   for(k in obj) {
       myDefault[k] = obj[k] ;
       myData[k]    = obj[k] ;
   }
   var gotKey = function(k) {
       for(kk in myDefault) {
           if(kk == k) return true ;
       }
       return false ;        
   } ;
   this.hasKey = gotKey ;
   var checkKey = function(k) {
       if(!gotKey(k))
           throw keyError ;
   } ;
  
   this.getItem = function(k) {
       checkKey(k) ;
       return myData[k];
   } ;
   
   this.setItem = function(k, v) {
       checkKey(k) ;
       myData[k] = v ;
   } ;
   
   this.resetItem = function(k) {
       checkKey(k) ;
       myData[k] = myDefault[k] ;      
   } ;
   
   this.delItem = this.resetItem ;
   
   this.clear   = function() {
       for(k in myDefault)
           myData[k] = myDefault[k] ;
   } ;
   
   this.iterator = function() {
       for(k in myDefault)
           yield (k);            
   } ;
   
   this.clone    = function() {
       return new FixedKeyDict(myDefault) ;
   }
   
   this.toStr = function() {
       var s = "" ;
       for(key in myData)
           s = s + key + " => " + myData[key] + ", " ;
       return "FixedKeyDict{" + s + "}" ;
   } ; 

}</lang>

Test run:

<lang javascript> const BR = "
\n"

var pl = function(s) {

   document.write(s + BR) ;

} ;

pl("

") ;

var o = { foo:101, bar:102 } ;

var h = new FixedKeyDict(o) ;
pl("Fixed Key Dict Created") ;
pl("toString   : " + h.toStr()) ;
pl("get an item: " + h.getItem("foo")) ;
pl("check a key: " + h.hasKey("boo")) ;
pl("ditto      : " + h.hasKey("bar")) ;
h.setItem("bar", 999) ;
pl("set an item: " + h.toStr()) ;
pl("Test iterator (or whatever)") ;
for(k in h.iterator())
    pl("  " + k + " => " + h.getItem(k)) ;
var g = h.clone() ;
pl("Clone a dict") ;
pl("  clone    : " + g.toStr()) ;
pl("  original : " + h.toStr()) ;
h.clear() ;
pl("clear or reset the dict") ;
pl("           : " + h.toStr()) ;
try {
    h.setItem("NoNewKey", 666 ) ;
} catch(e) {
    pl("error test : " + e.message) ;
}
</lang>

output :

<pre>
Fixed Key Dict Created
toString   : FixedKeyDict{foo => 101, bar => 102, }
get an item: 101
check a key: false
ditto      : true
set an item: FixedKeyDict{foo => 101, bar => 999, }
Test iterator (or whatever)
  foo => 101
  bar => 999
Clone a dict
  clone    : FixedKeyDict{foo => 101, bar => 102, }
  original : FixedKeyDict{foo => 101, bar => 999, }
clear or reset the dict
           : FixedKeyDict{foo => 101, bar => 102, }
error test : Invalid Key Error (FixedKeyDict)

Ruby

This example is under development. It was marked thus on 15/February/2011. Please help complete the example.

TODO: Add missing methods (FencedHash#delete_if). Write missing comments. Do more tests.

<lang ruby># fencedhash.rb require 'forwardable'

unless defined? KeyError

 KeyError = IndexError

end

  1. A FencedHash acts like a Hash, but with a fence around its keys.
  2. After the creation of a FencedHash, one cannot add nor remove keys.
  3. Any attempt to insert a new key will raise KeyError. Any attempt to
  4. delete a key-value pair will keep the key but will reset the value to
  5. the default value.

class FencedHash < Object

 extend Forwardable
 include Enumerable
 #--
 # @hash: our Hash inside the fence
 # @default_proc: passes self, not @hash
 #++
 def_delegators(:@hash, :[], :assoc,
                :compare_by_identity, :compare_by_identity?,
                :default, :empty?, :fetch, :flatten,
                :has_key?, :has_value?, :hash, :include?,
                :key, :key?, :keys, :length, :member?,
                :rassoc, :size, :to_a, :values, :values_at)
 attr_reader :default_proc
 # Acts like Hash::[] but creates a FencedHash.
 def self.[](*args)
   FencedHash.allocate.instance_eval do
     @hash = Hash[*args]
     self
   end
 end
 # call-seq:
 #   FencedHash.new(obj=nil [,keys])               -> fh
 #   FencedHash.new([keys]) { |fh, key| block }    -> fh
 #
 # Creates a FencedHash.....
 def initialize(*args, &block)
   if arguments.length > (block_given? && 1 || 2)
     raise ArgumentError, "wrong number of arguments"
   end
   super()
   if block_given?
     @default_proc = block
     @hash = Hash.new { |hash, key| yield self, key }
   else
     # FencedHash.new() acts like FencedHash.new(nil) because
     # if args.empty?, then args.shift returns nil.
     @hash = Hash.new(args.shift)
   end
   # For all keys in the fence, insert their default values.
   unless args.empty?
     args.first.each { |key| @hash[key] = @hash[key] }
   end
 end
 # Clears all values. For each key-value pair, this retains the key
 # but resets the value to default.
 def clear
   @hash.each_key { |key| delete key }
   self
 end
 # .....
 def default=(obj)
   @default_proc = nil
   @hash.default = obj
 end
 # .....
 def default_proc=(proc_obj)
   # Convert _proc_obj_ to a block parameter.
   proc_obj = proc &proc_obj
   @hash.default_proc = proc { |hash, key| proc_obj[self, key] }
   @default_proc = proc_obj
 end
 # Deletes the value of the key-value pair for _key_.
 #
 # If _key_ is in the fence.....
 def delete(key)
   begin
     original_value = @hash.fetch(key)
   rescue KeyError
     # _key_ is not in the fence.
     if block_given?
       yield key
     else
       @hash[key]
     end
   else
     # _key_ is in the fence. Must reset the value. From Ruby 1.9,
     # @hash remembers the insertion order of the keys. Must preserve
     # this insertion order and must not call @hash.delete(key).
     default = if @default_proc
                 @default_proc[self, key]
               else
                 @hash.default
               end
     @hash.store(key, default)
     original_value
   end
 end
 # Stores a _value_ for a _key_. This only works if _key_ is in the
 # fence; FencedHash prevents the insertion of new keys. If _key_ is
 # not in the fence, then this method raises KeyError.
 def store(key, value)
   if @hash.has_key? key
     @hash.store(key, value)
   else
     raise KeyError, "inserting new key: #{key}"
   end
 end
 alias []= store

end</lang>

<lang ruby># fh-test.rb require 'fencedhash' require 'test/unit'

class TestFencedHash < Test::Unit::TestCase

 def setup
   @fh = FencedHash[:q => 11, :w => 22, :e => 33,
                    :r => 44, :t => 55, :y => 66]
 end
 def test_bracket_operator
   assert_equal 11, @fh[:q]
   assert_equal 22, @fh[:w]
   assert_equal 33, @fh[:e]
   assert_equal 44, @fh[:r]
   assert_equal 55, @fh[:t]
   assert_equal 66, @fh[:y]
   assert_nil @fh["q"]
 end
 def test_fetch
   assert_equal 11, @fh.fetch(:q)
   assert_equal 22, @fh.fetch(:w)
   assert_equal 33, @fh.fetch(:e)
   assert_equal 44, @fh.fetch(:r)
   assert_equal 55, @fh.fetch(:t)
   assert_equal 66, @fh.fetch(:y)
   assert_raises(KeyError) { @fh.fetch "q" }
 end
 def test_keys
   sort = proc { |a| a.sort_by { |o| o.to_s }}
   assert_equal sortq, :w, :e, :r, :t, :y, sort[@fh.keys]
 end
 def test_length
   assert_equal 6, @fh.length
   assert_equal 6, @fh.size
 end
 if RUBY_VERSION >= "1.9"
   def test_insertion_order
     assert_equal [:q, :w, :e, :r, :t, :y], @fh.keys
   end
 end

end</lang>