Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > Javascript > Syntax for object comprehension?

Reply
Thread Tools

Syntax for object comprehension?

 
 
Dmitry A. Soshnikov
Guest
Posts: n/a
 
      01-31-2010
On Jan 30, 11:21*pm, G <culturea...@gmail.com> wrote:
> Ah, wait, __iterator__() to the rescue. *No key array needed! *Of
> course getStorageData() doesn't really return {} items, but it behaves
> as if it did in for each loops.
>
> function getStorageData() {
> * * * * return { "__iterator__": function() {
> * * * * * * * * * * * * let loop = 0;
> * * * * * * * * * * * * while( loop < localStorage.length ) {
> * * * * * * * * * * * * * * * * let key = localStorage.key( loop );
> * * * * * * * * * * * * * * * * yield [key, localStorage.getItem( key )];
> * * * * * * * * * * * * * * * * ++loop;
> * * * * * * * * * * * * }
> * * * * * * * * * * * * throw StopIteration;
> * * * * * * * * }
> * * * * };
>
> }
>


Yeah, __iterator__ (generator-based in your case; also you can you
special iterator object with .next method) - is a good decision in
this case. Although, there's still array on exit and you need to
define first object and then fill it with __iterator__ yielding
result.

/ds
 
Reply With Quote
 
 
 
 
Dmitry A. Soshnikov
Guest
Posts: n/a
 
      01-31-2010
On Jan 31, 9:05*am, G <culturea...@gmail.com> wrote:

[...]

>
> Maybe it's a Python itch?
>


Yes, array comprehension was borrowed to JavaScript(trade mark) from
Python, but in Python in difference from JS that's not possible to
fill some object iteration dictionary via array comprehension:

[(v, k) for v, k in {'a': 1, 'b': 2}.items()]

Result: [('a', '1'), ('b', 2)]

[a[v] = k for v, k in {'a': 1, 'b': 2}.items()] # syntax error

for v, k in {'a': 1, 'b': 2}.items(): # OK
a[k] = v

Also, there's no "object comprehension" in Python.

/ds
 
Reply With Quote
 
 
 
 
G
Guest
Posts: n/a
 
      01-31-2010
True, there aren't 'object comprehensions' in Python, but they can be
faked.

import math
sintable = dict( ([degree, math.sin( degree )] for degree in range( 0,
360 )) )
print sintable

While it would be nice to have something similar in JavaScript; for
loops and __iterator__() definitions seem to suffice (I'm not familiar
with JavaScript internals, so I don't know if comprehensions could be
optimized). Anyway, thanks for the discussion everyone, it was
educational!

Meanwhile, back at the creature feep (in case anyone is interested)...

function getLocalStorageKeyValues( criteriafunction ) {
return { "__iterator__": function() {
let key = undefined;
let loop = 0;
while( loop < localStorage.length ) {
key = localStorage.key( loop );
if( key && (typeof criteriafunction != 'function' ||
criteriafunction( key )) ) {
yield [key, localStorage.getItem( key )];
}
++loop;
}
throw StopIteration;
}
};
}

for( let [key, val] in getLocalStorageKeyValues() ) { //...

for( let [key, val] in getLocalStorageKeyValues( function( key )
key.indexOf( 'someprefix' ) === 0 ) ) { //...

--
G
 
Reply With Quote
 
Thomas 'PointedEars' Lahn
Guest
Posts: n/a
 
      01-31-2010
G wrote:

> Sorry about that,


About *what*? Learn to post.

<http://jibbering.com/faq/#posting>

> [...]
> I'd like to be able to define 'object comprehensions' like array
> comprehensions, in JavaScript, with key:values ({}) instead of values
> ([]).


{
key1: value1,
key2: value2
}

> Maybe it's a Python itch?


Maybe you don't know what you are talking about.

> As pointed out


You pointed out nothing. You posted some bogus code without saying what
you expect from it. Hence my asking.

> [TLDR]



PointedEars
--
Use any version of Microsoft Frontpage to create your site.
(This won't prevent people from viewing your source, but no one
will want to steal it.)
-- from <http://www.vortex-webdesign.com/help/hidesource.htm> (404-comp.)
 
Reply With Quote
 
Dmitry A. Soshnikov
Guest
Posts: n/a
 
      01-31-2010
On Jan 31, 4:48*pm, G <culturea...@gmail.com> wrote:
> True, there aren't 'object comprehensions' in Python, but they can be
> faked.
>
> import math
> sintable = dict( ([degree, math.sin( degree )] for degree in range( 0,
> 360 )) )
> print sintable
>


Hey, completely true, as I practice Python not so often (more
theoretically) forgot that `dict' callable class can accept array with
arrays (or tuples) for dictionary items. So result which you have from
array comprehension can be easily converted to dict-object:

dict([('a', 1), ('b', 2)]) # {'a': 1, 'b': 2}

You can create absolutely the same object-builder from passed array of
arrays as argument in JavaScript function and reuse it then.


>
> Meanwhile, back at the creature feep (in case anyone is interested)...
>
> function getLocalStorageKeyValues( criteriafunction ) {
> * * * * return { "__iterator__": function() {
> * * * * * * * * * * * * let key = undefined;
> * * * * * * * * * * * * let loop = 0;
> * * * * * * * * * * * * while( loop < localStorage.length ) {
> * * * * * * * * * * * * * * * * key = localStorage.key( loop );
> * * * * * * * * * * * * * * * * if( key && (typeof criteriafunction != 'function' ||
> criteriafunction( key )) ) {
> * * * * * * * * * * * * * * * * * * * * yield [key, localStorage.getItem( key )];
> * * * * * * * * * * * * * * * * }
> * * * * * * * * * * * * * * * * ++loop;
> * * * * * * * * * * * * }
> * * * * * * * * * * * * throw StopIteration;
> * * * * * * * * }
> * * * * };
>
> }
>
> for( let [key, val] in getLocalStorageKeyValues() ) { //...
>
> for( let [key, val] in getLocalStorageKeyValues( function( key )
> key.indexOf( 'someprefix' ) === 0 ) ) { //...
>


Yep, that's interesting implementation, although, all the iterator
object can be cached (as an optimization for do not create object each
time) in `getLocalStorageKeyValues' as a static property and reused
then:

function getLocalStorageKeyValues(criteriafunction) {

// set each time new criteriafunction
getLocalStorageKeyValues.criteriafunction = criteriafunction;

// but return always the same object
return getLocalStorageKeyValues.iteratorObject;
}

getLocalStorageKeyValues.iteratorObject = {__iterator__: ...};

and inside the getLocalStorageKeyValues.iteratorObject use:

if( key && (typeof getLocalStorageKeyValues.criteriafunction !=
'function' ||
getLocalStorageKeyValues.criteriafunction( key )) ) {

There can be difference in `this' value inside the call of
criteriafunction, but that doesn't heart your case.

/ds
 
Reply With Quote
 
Dmitry A. Soshnikov
Guest
Posts: n/a
 
      01-31-2010
On Jan 31, 5:21*pm, "Dmitry A. Soshnikov" <dmitry.soshni...@gmail.com>
wrote:

[...]

> dict([('a', 1), ('b', 2)]) # {'a': 1, 'b': 2}
>
> You can create absolutely the same object-builder from passed array of
> arrays as argument in JavaScript function and reuse it then.
>


Small addition: although it's possible to do it in this way (and also
in JS), there will be additional full iteration inside the `dict'
function (callable class), first to get array from array
comprehension, the second one - to create the dictionary from the
array parameter:

d = dict([(v, k) for v, k in {'a': 1, 'b': 2}.items()])

Meanwhile in JS will be only one iteration for that:

[o[key] = value for ([key, value] in Iterator({a: 1, b: 2}))];

/ds
 
Reply With Quote
 
G
Guest
Posts: n/a
 
      01-31-2010
It's comforting to know that USENET hasn't changed much after all
these years.

--
G
 
Reply With Quote
 
G
Guest
Posts: n/a
 
      01-31-2010
Would caching allow multiple interleaved uses, without conflicts? I
was assuming the present implementation of getLocalStorageKeyValues()
would allow for multiple interleaved clients, with different filtering
criteria. For example, I was hoping to use Worker instances and
localStorage together (assuming Worker instances can access
localStorage, I haven't experimented with Worker yet). Hmmm, maybe
Worker scope is isolated, including any potential
getLocalStorageKeyValues() states...

In that other language; I should have used the example from the Python
docs (thought it wasn't as obvious what was going on, perhaps it is
actually clearer).

dict( (x, sin( x * pi / 180 )) for x in range( 0, 91 ) )

That's a generator expression being passed to dict(), a tuple at a
time. I assume that minimizes the intermediates involved.

I do like the o = {}; [o[k] = v ...] trick (for JavaScript). Without
running some benchmarks, I don't know which would be most performant
(I'd guess for loops, due to the lack of function calls).

--
G
 
Reply With Quote
 
Dmitry A. Soshnikov
Guest
Posts: n/a
 
      01-31-2010
On Jan 31, 7:00*pm, G <culturea...@gmail.com> wrote:
> Would caching allow multiple interleaved uses, without conflicts? *I
> was assuming the present implementation of getLocalStorageKeyValues()
> would allow for multiple interleaved clients, with different filtering
> criteria. *For example, I was hoping to use Worker instances and
> localStorage together (assuming Worker instances can access
> localStorage, I haven't experimented with Worker yet). *Hmmm, maybe
> Worker scope is isolated, including any potential
> getLocalStorageKeyValues() states...
>


Sure if some different objects should use it with own criteria (and
especially with Workers) it's not acceptable. But in this case would
be better to put iterator function into the prototype (which means,
all instances will have their own state, but will share one
__iterator__ function):

function getLocalStorageKeyValues(criteriaFn) {
...
this.criteriaFn = criteriaFn;
...
}

getLocalStorageKeyValues.prototype.__iterator__ = function () {
if (this.criteriaFn(...)) {
...
}
};

var first = new getLocalStorageKeyValues(function () {...});
var second = new getLocalStorageKeyValues(function () {...});

But, that's just a suggestion, do in most comfortable way.

/ds
 
Reply With Quote
 
 
 
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
Syntax Checker that's better than the normal syntax checker Jacob Grover Ruby 5 07-18-2008 05:07 AM
Syntax bug, in 1.8.5? return not (some expr) <-- syntax error vsreturn (not (some expr)) <-- fine Good Night Moon Ruby 9 07-25-2007 04:51 PM
[ANN] SqlStatement 1.0.0 - hide the syntax of SQL behind familiarruby syntax Ken Bloom Ruby 3 10-09-2006 06:46 PM
Syntax highligth with textile: Syntax+RedCloth ? gabriele renzi Ruby 2 12-31-2005 02:44 AM
Object creation - Do we really need to create a parent for a derieved object - can't the base object just point to an already created base object jon wayne C++ 9 09-22-2005 02:06 AM



Advertisments