Skip to content

Instantly share code, notes, and snippets.

@z2015
Created July 5, 2016 01:22
Show Gist options
  • Select an option

  • Save z2015/5795a0ef040e61701ddce6dafefd8227 to your computer and use it in GitHub Desktop.

Select an option

Save z2015/5795a0ef040e61701ddce6dafefd8227 to your computer and use it in GitHub Desktop.
For Loop inner Object Assignment with Test.
require('chai').should();
var expect = require('chai').expect;
var assert = require('chai').assert;
function xybkPushSame(dt){
var xybk = [];
var obj = {};
for (let i=0; i<dt.length; i++){
obj.title = dt[i].title;
obj.id = dt[i].id;
xybk.push(obj);
}
return xybk;
}
function xybkPushNotSame(dt){
var xybk = [];
for (let i=0; i<dt.length; i++){
var obj = {};
obj.title = dt[i].title;
obj.id = dt[i].id;
xybk.push(obj);
}
return xybk;
}
Array.prototype.foo = "foo!";
function forinVersion(dt){
var xybk = [];
for (var i in dt){
if (dt[i].title){
xybk.push(dt[i]);
}
}
return xybk;
}
function mapVersion(dt){
var cb = function(elem){
if (elem.title) return elem;
}
var xybk = dt.map(cb);
return xybk;
}
var dt = [{id: 13, title: 'first'}, {id: 14, title:'Second'}, {id: 15, title:'Third'}];
var dtSame = [{id: 15, title:'Third'}, {id: 15, title:'Third'}, {id: 15, title:'Third'}];
describe('XYBK', function(){
describe('tran', function(){
it('should return same right value within obj declared out of the loop', function(){
var result = xybkPushSame(dt);
assert.deepEqual(result, dtSame, 'with same last obj.');
});
it('should return right value with for loop', function(){
var result = xybkPushNotSame(dt);
result.should.deep.equal(dt);
});
it('should return right value with for in loop', function(){
var result = forinVersion(dt);
expect(result).to.deep.equal(dt);
});
it('should return right value with map', function(){
var result = mapVersion(dt);
expect(result).to.deep.equal(dt);
});
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment