473,779 Members | 2,062 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Vector data type (2nd attempt)

VK
A while ago I wrote a "Vector data type" script
using DOM interface to select.options.
That was a (beautiful) mind game :-) rather than
a practical thing to use.

Here is another attempt open for criticism, this
time dead serious. I really need an effective
Vector emulator for a project (as much effective
as something not implemeted in language but
emulated by means of the language itself is: a
productivity impact is imminent, the question
is to minimize it).
<html>
<head>
<title>Vector constructor</title>
<meta http-equiv="Content-Type"
content="text/html; charset=iso-8859-1">
<script>
function Vector(arr) {
this.$_$ = arr || new Array();
this.length = this.$_$.length ;
this.add = Vector.$add;
this.remove = Vector.$remove;
this.toString = Vector.$toStrin g;
}

Vector.$add = function(m,i) {
if (('number'!=typ eof(i))||(i<0)| |(i>=this.$_$.l ength)) {
this.$_$.push(m );
}
else {
var tmp = [m];
tmp.push(this.$ _$[i]);
this.$_$.splice (i,1,tmp);
}
this.length = this.$_$.length ;
}

Vector.$remove = function(i) {
var ret = this.$_$.splice (i,1)[0];
this.length = this.$_$.length ;
return ret;
}

Vector.$toStrin g = function() {
return this.$_$.toStri ng();
}

// Create new vector and use it as a wrapper
// over Array argument:
var v = new Vector([1,2,3]);

// add(newElement, atPosition) method
// if no atPosition provided, newElement will
// be added to the top
v.add(4); // add 4 to the top

// Add 3.5 atPosition 3
// The element currently located at v[3] and all elements atop
// of it will be moved one position up
v.add(3.5, 3);

// remove(atPositi on) method
// Elements currently located atop of it will be moved
// one position down
v.remove(1);

// toString method is overloaded so in string
// context it gives comma-separated vector values
alert(v); //1, 3, 3.5, 4
</script>
</head>

<body>

</body>
</html>

Sep 13 '06
28 1953
In article <11************ **********@i3g2 000cwc.googlegr oups.com>, VK
<sc**********@y ahoo.comwrites
>List data type v.2

1) Correct term use (List not Vector): Ray, Harris
2) splice() to insert an element optimization: Ray
<html>
<head>
<title>List constructor</title>
<meta http-equiv="Content-Type"
content="text/html; charset=iso-8859-1">
<script>
function List(arr) {
this.$_$ = arr || new Array();
this.length = this.$_$.length ;
this.add = List.$add;
this.remove = List.$remove;
this.toString = List.$toString;
}
<snip>

Why don't you give List objects a prototype ?

>P.S. what do $add, $remove and so names (starting with $)? Just a
marker of identifiers used only internally (that would be "private"
modifier if existed). Some are using underscores instead (_add,
_remove), but it is really an in-company choice, could be even prvtAdd,
prvtRemove. That is to make the track of vars easier and - if needed -
to have one click conversion to JScript.NET
length needs to be Read Only a lot more than the internal array needs to
be private. If someone changes a List object's length value then you're
scuppered. A length() method accessing the object's array would be a lot
safer.

John
--
John Harris
Sep 15 '06 #21
VK wrote:
List data type v.2
1) Correct term use (List not Vector): Ray, Harris
Do you understand Java? List is an interface. You cannot create a "List"
object.
Further, you only implemented two of its methods, and one of them has a
different argument order. Why even try to make your js look like Java?
2) splice() to insert an element optimization: Ray
How about:
3) Just enhance Array and call it List then: Matt

The following code is much simpler:

----------
Array.prototype .add = function(elemen t,index) {
if (('number'!=typ eof index)||(index> =this.length)) {
this.push(eleme nt);
}
else {
this.splice(ind ex,0,element);
}
}
Array.prototype .remove = function(index) {
if (('number' != typeof index)||(index >= this.length)) {
return null;
}
else {
if (index<0) {index -= this.length;}
return this.splice(ind ex,1)[0];
}
}
var List = Array;
----------

Now, what value does it add? None, really. Under the hood, you're still just
using Array methods. So why not just call it an Array? You're not adding any
value by creating this "List" object.

--
Matt Kruse
http://www.JavascriptToolbox.com
http://www.AjaxToolbox.com
Sep 16 '06 #22
VK
John G Harris wrote:
Why don't you give List objects a prototype ?
That is another fully viable option, see the reply by Matt Kruze
length needs to be Read Only a lot more than the internal array needs to
be private. If someone changes a List object's length value then you're
scuppered. A length() method accessing the object's array would be a lot
safer.
Yeh, and have typos all around with length called as property (w/o
parenthesis) :-(
I tried it already in another object. That is not even a programming
issue but an ergonomical one (damn human factor). In this aspect it
seems better then to use VB approach and to have a stay-alone function
for length:
len(myList); // length(myList); ?
That is another thing I'm missing terribly in ECMAScript: an ability to
have compound properties (objects with getter/setter) and respectively
read-only / write-only options for them, not just fields as it is now.
That is a breeze with HTC/XBL. In the regular inline script I once
twisted my mind around of thinking a way to call a function as a
property, but no way. The only trick is available in string context by
overloading toString method.

Sep 16 '06 #23
VK
Matt Kruse wrote:
List is an interface.
You cannot create a "List" object.
Think of "myArray extends Array implements List", that helps ;-)

How about:
Just enhance Array and call it List then
Another fully viable option.

----------
Array.prototype .add = function(elemen t,index) {
if (('number'!=typ eof index)||(index> =this.length)) {
this.push(eleme nt);
}
else {
this.splice(ind ex,0,element);
}
}

Array.prototype .remove = function(index) {
if (('number' != typeof index)||(index >= this.length)) {
return null;
}
else {
if (index<0) {index -= this.length;}
return this.splice(ind ex,1)[0];
}
}

var List = Array;
----------
Now, what value does it add? None, really. Under the hood, you're still just
using Array methods. So why not just call it an Array? You're not adding any
value by creating this "List" object.
That is a question of the kind "Why do you need to create class Manager
if it has only one property more than Employee? Simply add that
property to an Employee instance."

Or more generally: "Why do you need OOP hassle? Your custom objects do
not do anything what their supers couldn't, so just augment supers".
:-)

Having the prototype way as totally correct option, I need (think I
need, want) a separate object type, not just Array with extra methods.
Array is hadled as a fixed continuum defined by 0 - (length-1) borders.
We can extend this continuum or make "holes" ("gaps") in this continuum
by delete'ing elements.
List (interface) is flexible continuum able to automatically expand and
collapse ("healing the holes") on elements adding/removal.
That seems as enough of behavioral difference for a will to have two
different objects from different constuctors: rather than all existing
and future Array's acting this way or that way depending on what
methods do you apply to them.

Once again: prototype augmentation is definitely and always an option.

Sep 16 '06 #24
VK

VK wrote:
... see the reply by Matt Kruze ...
How many times I did this damn typo...

Matt *Kruse*

Sep 16 '06 #25
VK wrote:
<snip>
function List(arr) {
this.$_$ = arr || new Array();
this.length = this.$_$.length ;
this.add = List.$add;
this.remove = List.$remove;
this.toString = List.$toString;
}
List.$add = function(m,i) {
<snip>
}
List.$remove = function(i) {
<snip>
}
<snip>
List.$toString = function() {
return this.$_$.toStri ng();
}
<snip>
P.S. what do $add, $remove and so names (starting
with $)? Just a marker of identifiers used only
internally (that would be "private" modifier if
existed).
<snip>

It would still be more efficient to be creating the methods as
properties of the object's prototype and so having them inherited by the
objects constructed (instead of explicitly assigning them) and then
there is no reason for using (poorly chosen) naming conventions to
discourage people form using them in the context where they are exposed.

Richard.
Sep 16 '06 #26

Ray wrote:
VK wrote:
Here is another attempt open for criticism, this
time dead serious. I really need an effective
Vector emulator for a project (as much effective
as something not implemeted in language but
emulated by means of the language itself is: a
productivity impact is imminent, the question
is to minimize it).
<snip>

As a long time Java programmer and newbie in JavaScript--I wonder--what
kind of value does your Vector add on top of JavaScript's existing
Array? Vector was created in Java because Java's Array is nowhere as
flexible as JavaScript's. Not so with JS's Array.

The methods exposed by your Vector class don't add value to what one
does with JS Array--if you think I'm wrong, I'll be glad to be
corrected.

(and what is with the $add and stuff? They're weird.)
Which leads to ask why Vector and not java.util.List ? Nobody
programming java since version 1.2 should be using Vector. It was
implemented for the reason you pointed out and used becasue there was
nothing better at the time. Promoting the use of a (admitted by Sun)
broken API just doesn't seem like a good idea. As a java programmer he
should know that best practices recommend programming toward interfaces
and not the concrete classes, especially so when it comes the the
Collections API.
If a synchronized list is desired, then the static method
"synchronizedLi st(List)" should be called on the java.util.Colle ctions
class.

OTOH, it looks like all he is really after is the ability to add an
item at a particualr index and shift the other items, and remove a
particular item and have everything shift back. Which is really much
less than the methods defined in Vector. Seems like the KISS priciple
would dictate just adding these methods to objects of type Array using
the evil prototype.

Sep 18 '06 #27

VK wrote:
John G Harris wrote:
In article <11************ **********@e3g2 000cwe.googlegr oups.com>, VK
<sc**********@y ahoo.comwrites

<snip>
this.add = Vector.$add;
this.remove = Vector.$remove;
<snip>

Looks more like a List than a Vector.

For me it looks more like a Vector than a List :-)

<http://java.sun.com/j2se/1.3/docs/api/java/util/Vector.html>
<http://java.sun.com/j2se/1.4.2/docs/api/java/util/List.html>
Try re-reading the Javadocs.
Vector implements the interface List. List defines the methods. An
interface can not be a derivative of a class.
>From the Javadoc for List pertinent to what you are trying to do:
void add(int index, Object element)
Object remove(int index)

Take a look at the documentation of the Collections framework:
http://java.sun.com/j2se/1.4.2/docs/.../overview.html
>From my previous post, Vectors as a rule should be avoided (unless you
are targeting a JVM1.1 or older).

Sep 18 '06 #28

VK wrote:
Matt Kruse wrote:
List is an interface.
You cannot create a "List" object.

Think of "myArray extends Array implements List", that helps ;-)

How about:
Just enhance Array and call it List then

Another fully viable option.

----------
Array.prototype .add = function(elemen t,index) {
if (('number'!=typ eof index)||(index> =this.length)) {
this.push(eleme nt);
}
else {
this.splice(ind ex,0,element);
}
}

Array.prototype .remove = function(index) {
if (('number' != typeof index)||(index >= this.length)) {
return null;
}
else {
if (index<0) {index -= this.length;}
return this.splice(ind ex,1)[0];
}
}

var List = Array;
----------
Now, what value does it add? None, really. Under the hood, you're still just
using Array methods. So why not just call it an Array? You're not adding any
value by creating this "List" object.

That is a question of the kind "Why do you need to create class Manager
if it has only one property more than Employee? Simply add that
property to an Employee instance."

Or more generally: "Why do you need OOP hassle? Your custom objects do
not do anything what their supers couldn't, so just augment supers".
:-)

Having the prototype way as totally correct option, I need (think I
need, want) a separate object type, not just Array with extra methods.
Array is hadled as a fixed continuum defined by 0 - (length-1) borders.
We can extend this continuum or make "holes" ("gaps") in this continuum
by delete'ing elements.
List (interface) is flexible continuum able to automatically expand and
collapse ("healing the holes") on elements adding/removal.
That seems as enough of behavioral difference for a will to have two
different objects from different constuctors: rather than all existing
and future Array's acting this way or that way depending on what
methods do you apply to them.

Once again: prototype augmentation is definitely and always an option.
Since this looks like its getting out of control and Matt was the only
one kind enough to post code, I'm going to offer up the following as
well.
In keeping with the java.util.List inteface, I'm going to give the
size() method instead of length. I am also going to internalize the
methods of the List object. The constructor in this method will copy
the supplied array to prevent its modification (as in VK's posted
code).
I am also adding a few xUnit type tests to validate functionality and
to document usage.
I Hope it helps to clarify what others have been trying to explain.

<html>
<head>
<title>List in JS</title>
</head>

<script type="text/javascript">

function List(srcAry){
this._internAry = new Array();
if(srcAry){
/* Copy supplied array to prevent side effects */
this._internAry = new Array(srcAry.le ngth);
for(var i=0;i<srcAry.le ngth;i++){
this._internAry[i] = srcAry[i];
}
}
this.add = function(obj,in dx){
this._internAry .splice(indx,1, obj)
};
this.remove = function(indx){
return this._internAry .splice(indx,1) ;
};
this.toString = function(){
return this._internAry .toString();
}
this.size = function(){
return this._internAry .length;
}
}
</script>

<script type="text/javascript">
function assertEquals(ms g,val1,val2){
if(val1 != val2){
alert(msg + "\n expected: "+val1+"\nrecei ved: "+val2);
arguments.calle e.failed = +arguments.call ee.failed || 0;
arguments.calle e.failed++;
}
}
// Tests
var srcAry = new Array('Apples', 'Oranges','Bana nas');
assertEquals("S hould be 3 fruit",3,srcAry .length);

var myList = new List(srcAry);
assertEquals("t oString test
failed","Apples ,Oranges,Banana s",myList.toStr ing());
assertEquals("i ncorrect size on construction",3 ,myList.size()) ;

myList.add('Str awberries', 3);
assertEquals("S ize failed after adding",4,myLis t.size());
assertEquals("t oString test
failed","Apples ,Oranges,Banana s,Strawberries" ,myList.toStrin g());
assertEquals("S ource array modified (bad juju)",3,srcAry .length);

var fruit1 = myList.remove(1 );
assertEquals("w rong fruit","Oranges ",fruit1);
assertEquals("r esize failed after remove",3,myLis t.size());
assertEquals("t oString test
failed","Apples ,Bananas,Strawb erries",myList. toString());
assertEquals("S ource array modified (bad juju)",3,srcAry .length);

var fruit2 = myList.remove(1 );
assertEquals("w rong fruit","Bananas ",fruit2);
assertEquals("r esize failed after remove",2,myLis t.size());
assertEquals("t oString test
failed","Apples ,Strawberries", myList.toString ());
assertEquals("S ource array modified (bad juju)",3,srcAry .length);

if(assertEquals .failed){
alert("tests failed: " + assertEquals.fa iled);
}else{
alert("All tests passed");
}
</script>
<body>

</body>
</html>

Sep 18 '06 #29

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
2270
by: lawrence | last post by:
I had some code that worked fine for several weeks, and then yesterday it stopped working. I'm not sure what I did. Nor can I make out why it isn't working. I'm running a query that should return 3 items from the database. I then get a count of the return, which correctly tells me that I've got 3 items. I then go into a for loop which I expect to loop 3 times and print out the 3 items. Here is where things get strange: it loops 3 times and...
0
1367
by: Row | last post by:
HI, I would first like to say its been about 3 years since looking at java im very rusty! I have to write a post it notes type applet which will function online. (reading from a flat text file) My main problem is: getting each paragraph into my vector array - so that each paragraph sits in a new array element. Eg: when i referance array elemant 2 it will give me paragraph which is in that element and not all paragraphs in the text file...
12
5717
by: arnuld | last post by:
in C++ Primer 4/3 Lippman says in chapter 3, section 3.3.1: vector<stringsvec(10); // 10 elements, each an empty string here is the the code output & output from my Debian box running "gcc 3.3.5": #include <iostream> #include <vector>
4
1508
by: Brian C | last post by:
Hello all, I was playing around (don't know why, perhaps bored at work) with the vector class. This was on an AIX machine using IBM's xlC compiler. Anyway, I wrote a simple class, and inserted it a couple of times into a vector. What I found odd was that when I inserted the 2nd item, I saw that it called my copy constructor for the 1st item and the 2nd item. When I inserted the 3rd object, it called the copy constructor for the...
0
2400
by: Jacob Donajkowski | last post by:
Once the user logs in I want to have the users switch from the Roster View to the Profile View and enter their profile infomation and save it. Then the next time they login and go to the Profile View I want the form populated from there profile on the sql server. The code to save the profile works fine. But when the user logs back in they data doesn't load back to the form. The multiview is located inside the LoginView's Logged-In View ....
3
1588
by: Rob | last post by:
I have these classes (elided methods): class Base { public: Base(string name) {...} }; class Derived : public Base {
19
1530
by: Ramon F Herrera | last post by:
Newbie alert: I come from the C side, struggling to learn C++. I need a two-dimensional data structure. I first tried a regular vector and added the 2nd dimension with my own structs and pointers. I couldn't make it work. Too many illegal assignments. My next attempt was to create a vector of vector (or list of vector, etc.). The compiler (MSVC++) doesn't seem to like such structure. I guess I could try gcc, but let's hear the experts'...
0
9474
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10138
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10074
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9930
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8961
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7485
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5373
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
4037
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
2869
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.