ram
8/22/2015 10:07:00 AM
Stone Zhong <stone.zhong@gmail.com> writes:
>Is there a member function in ES5 or ES6 doing something like below?
I am not aware of such a function.
>var forEachItemInObject = function(obj, callback) {
> var ret = [ ];
> for (var key in obj) {
> ret.push(callback(key, obj[key]));
> }
> return ret;
>};
The function is constantly pushing to ret here, that is, the
function is building an intermediate object. It might be
cheaper just to yield. For example,
function* map( f, value )
{ "use strict";
for( let key in value )yield f( key, value[ key ]); }
This can be used as in, for example:
( function()
{ "use strict";
function* map( f, value )
{ "use strict"; for( let key in value )yield f( key, value[ key ]); }
function output( string )
{ "use strict"; console.log( string + "\n" );
document.write( string + "\n" ); }
function main()
{ "use strict";
{ const value = Object.create( null ); value.alpha = "beta";
const f = function( key, value ){ output( key + ", " + value ); };
{ const iterator = map( f, value );
while( !iterator.next().done ); }}}
return main; }) () ();