Created
June 30, 2015 21:20
-
-
Save greenlikeorange/5467d3534f6e4fc4bda0 to your computer and use it in GitHub Desktop.
Normal and Functional Approach of Add/Replace Data Patten at JavaScript
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var oldDB = [ | |
{ | |
index: 1, | |
name: "Java" | |
}, | |
{ | |
index: 2, | |
name: "C" | |
}, | |
{ | |
index: 5, | |
name: "Rust" | |
} | |
]; | |
var newDB = [ | |
{ | |
index: 1, | |
name: "JavaScript" | |
}, | |
{ | |
index: 3, | |
name: "Ruby" | |
} | |
]; | |
function addOrReplaceWithIndex_NormalApproach(oldData, newData){ | |
var filteredOldData = []; | |
for (var i = 0; i < oldData.length; i++) { | |
var odata = oldData[i]; | |
var _index = odata.index; | |
// Filtering not match with new data | |
var match = false; | |
for (var j = 0; j < newData.length; j++) { | |
var ndata = newData[j]; | |
if(ndata.index === _index){ | |
match = true; | |
break; | |
} | |
} | |
if( !match ) | |
filteredOldData.push( odata ); | |
} | |
return filteredOldData.concat( newData ); | |
} | |
function addOrReplaceWithIndex_FunctionalApproach(oldData, newData){ | |
// Filtering not match with new data | |
var _filter = oldData.filter(function( odata ){ | |
/* | |
* NOTE: We can't do "Some of newData is not match with odata" | |
*/ | |
var indexIsIncludeInNewData = newData.some(function( ndata ){ | |
return ndata.index === odata.index; | |
}); | |
return !indexIsIncludeInNewData; | |
}); | |
return _filter.concat( newData ); | |
} | |
console.dir( addOrReplaceWithIndex_NormalApproach(oldDB, newDB) ); | |
console.dir( addOrReplaceWithIndex_FunctionalApproach(oldDB, newDB) ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment