Some tips and tricks

L

Lasse Reichstein Nielsen

John G Harris said:
The section 'shuffle the Array' looks rather dodgy.

Indeed. The "algorithm" is:
list = list.sort(function() Math.random() - 0.5)

What will happen depends on the underlying sorting algorithm, the only
thing that's safe to assume is that the shuffling will not have
an (approximatly) even distribution of the possible permutations.

If, e.g., it uses insertion sort (often used for small arrays), the
last element has a 50% chance of staying where it is, and 25% chance
of moving only one position.

It's not even remotely usable for actual shuffling.

(Not to mention that I've seen at least one sort implementation that
that didn't necessarily terminate for a non-stable comparison!)

/L
 
J

Jorge

Indeed. The "algorithm" is:
 list = list.sort(function() Math.random() - 0.5)

What will happen depends on the underlying sorting algorithm, the only
thing that's safe to assume is that the shuffling will not have
an (approximatly) even distribution of the possible permutations.

If, e.g., it uses insertion sort (often used for small arrays), the
last element has a 50% chance of staying where it is, and 25% chance
of moving only one position.

It's not even remotely usable for actual shuffling.

(Not to mention that I've seen at least one sort implementation that
that didn't necessarily terminate for a non-stable comparison!)


Yes...

http://groups.google.com/group/comp...0864cc96088/5d3754682dbf61db#d6bc5f084b91bf85
 
D

Dr J R Stockton

Fri said:
Indeed. The "algorithm" is:
list = list.sort(function() Math.random() - 0.5)

A smarter TC39 would have realised that shuffling is commonly badly
done, and therefore introduced SHUFFLE (and DEAL and DRAW) as new
methods of Array. Since they can be coded briefly and efficiently in
Pascal and JavaScript (using Random(N) [*]), there should be no
difficulty in doing likewise in JavaScript engine source code.

[*] <URL:http://www.merlyn.demon.co.uk/js-randm.htm>
 
A

abozhilov

You could do this as a faster alternative:

~~123.345456

In Ecma262 Number is double-precision 64-bit format IEEE 754. You
missed one general point. Bitwise operators cast Number to ToInt32();
So you can overflow 32 bits, and get unexpected results.

Math.floor(123.345456); //123
123.345456 - (123.345456 % 1); //123

Regards.
 
A

Asen Bozhilov


| function isNotEmpty(obj) {
| for ( var tmp in obj )
| return true
| }

What are you mean with that function "isNotEmpty"? For-in look up in
prototype chain and enumerate properties who's doesn't have attribute
{DontEnum}. In ECMA262 i don't know `object' who is empty, because
inherit from Object.prototype.

| Insert an array in another array
| var a = [1,2,3,4,5,6]
| var b = ['a','b','c']
| var insertIndex = 5;
| Array.concat( a.splice( 0, insertIndex ), b, a )

`splice' modified properties of `object' who refer `a'. See topic of
Csaba Gabor:
<URL:http://groups.google.com/group/comp.lang.javascript/browse_thread/
thread/ec2ffbc979c65cc4/ebc7570a2f3ea7aa?pli=1>

Regards/
 
M

Michael Haufe (\TNO\)

In Ecma262 Number is double-precision 64-bit format IEEE 754. You
missed one general point. Bitwise operators cast Number to ToInt32();
So you can overflow 32 bits, and get unexpected results.

Math.floor(123.345456); //123
123.345456 - (123.345456 % 1); //123

Regards.

Good catch.
 
G

Garrett Smith

Asen said:
| function isNotEmpty(obj) {
| for ( var tmp in obj )
| return true
| }

What are you mean with that function "isNotEmpty"? For-in look up in
prototype chain and enumerate properties who's doesn't have attribute
{DontEnum}. In ECMA262 i don't know `object' who is empty, because
inherit from Object.prototype.
AIUI, it means the object has no own properties.

The example has the footnote:
| The aim of this function is to detect properties directly on obj.

It fails if the program modifies Object.prototype. That can and should
avoided.
 
G

Garrett Smith

Jorge said:
The Singleton pattern:
| function MySingletonClass() {
|
| if ( arguments.callee._singletonInstance )
| return arguments.callee._singletonInstance;
| arguments.callee._singletonInstance = this;
|
| this.Foo = function() {
| // ...
| }
| }

There are a few downsides to that approach.

The singleton logic exists inside the constructor. A public
_singletonInstance property is exposed. Using arguments.callee prevents
an optimization in some implementations. Everything being in the
constructor can lead to a long constructor (most find long
methods or constructors harder to read and debug.

An alternative Singleton:

function createSingleton(buildCtor){
var instance;
return {
getInstance : getInstance
};
function getInstance(arg){
if(!instance) {
var ctor = buildCtor();
ctor.prototype = null;
instance = new ctor(arg);
}
return instance;
}
}

// Usage:
var AAA = createSingleton(
function(name) {
return AAA;
function AAA(name) {
this.name = name;
this.method = meth;
}
function meth(){
return 17;
}
}
);

That is similar to, though much simpler than APE.createFactory.

Longer scope chain lookup can be mitigated by aliasing local variables
in the scope of the function that return the constructor. Care must be
taken so as to not store reference to things that are not needed in
scope.

Those aliased variables benefit from fast lookup and munging (where
relevant). Those variables are not initialized unless AAA.getInstance is
called, e.g.:-

var AAA = createSingleton( ...

- is 1 function call (to createSingleton), the creation of one function
(the constructor) the creation of an object with a getInstance method,
plus two [[Scope]] objects (for each function).

1 object, 2 functions, 1 function call.

The |constructor| property is replaced with Object (the [[Prototype]] is
Object.prototype), making the Singleton truly private. With one less
object in the prototype chain, for-in enumeration will have less work.
 
A

Asen Bozhilov

AIUI, it means the object has no own properties.

The example has the footnote:
|  The aim of this function is to detect properties directly on obj.

It fails if the program modifies Object.prototype. That can and should
avoided.

Of course. You have in APE one method `mixin' who copy own properties.
Here we can use similar approach.

Object.hasOwnProperties = function(o)
{
for (var i in o)
{
if (o.hasOwnProperty(i)) return true;
}
return false;
};

Except {DontEnum} bug of JScript for properties `valueOf' and
`toString'.

Regards.
 
A

Asen Bozhilov

It would be safer to replace this with:

if (Object.prototype.hasOwnProperty.call(o, i)) { /* ... */ }

(probably also aliasing `Object.prototype.hasOwnProperty` for faster access)

When i write that code, i think about your suggestion. I don't think
Object.prototype.hasOwnProperty.call(o, i) is safer. I don't know what
is behavior of hasOwnProperty over a host object and i want to test
`object' who inherit `hasOwnProperty' from Object.prototype or
implement *own* `hasOwnProperty'. See below:

var a = '{DontDelete}';
Object.prototype.hasOwnProperty.call(this, 'a'); //true

Global execution context doesn't have Variable Object, for Variable
Object used Global Object. Every variable will be property of Global
Object but unlike other user defined properties of objects, they have
attribute {DontDelete}.

Another problem in global execution context is IE {DontEnum} bug:

p = 'IE {DontEnum}';
for (var i in this)
{
if (i == 'p') window.alert(this);
}
window.alert('p' in this); //true
 
A

Asen Bozhilov

var o = { 'hasOwnProperty': 'foo' };
o.hasOwnProperty('bar'); // TypeError

You can try testing for it, but why bother.
`Object.prototype.hasOwnProperty.call` doesn't have these problems.

Yes, but this can interpreted in different way. With
Object.prototype.hasOwnProperty.call you break implementation of *own*
`hasOwnProperty' of `object'. All of that is point of view. And for me
inherited `hasOwnProperty' or *own* is better from
Object.prototype.hasOwnProperty.call .

ThankÑ for link, usefully topic. I read it before when it was
released
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,743
Messages
2,569,478
Members
44,898
Latest member
BlairH7607

Latest Threads

Top