编程实践
常言道:”实践出真知” 。是骡子是马,拉出来遛遛才知道。所以,如果真的想搞懂这个原理,还是亲自写代码实践一下才是硬道理。
最近和几个朋友一起学习JavaScript,所以就比较关注JavaScript。昨天上网瞎逛时,惊奇地发现,竟然有牛人使用JavaScript实现了MapReduce算法。然后转过来和大家分享,同时再加上我自己的一些狗尾续貂的介绍,希望有助于大家理解MapReduce。具体代码实现如下:
代码如下:
var Job = {
//待处理的数据
data : [
"We are glad to see you here. This site is dedicated to",
"poetry and to the people who make poetry possible",
"poets and their readers. FamousPoetsAndPoems.com is",
"a free poetry site. On our site you can find a large",
"collection of poems and quotes from over 631 poets",
"Read and Enjoy Poetry",
"I, too, sing America",
"I am the darker brother",
"They send me to eat in the kitchen",
"When company comes",
"But I laugh",
"And eat well",
"And grow strong",
"Tomorrow",
"Ill be at the table",
"When company comes",
"Nobodyll dare",
"Say to me",
"Eat in the kitchen",
"Then",
"Besides",
"Theyll see how beautiful I am",
"And be ashamed",
"I, too, am America"
],
//将数据中的每行字符串用空格分隔开,
//并"重组"成诸如{key: 单词, value: 1}格式的对象,返回对象数组
map : function(line) {
var splits = line.split(" ");
var temp = [];
for(var i=0; i
}
return temp;
},
//计算每个单词在"数据"(data)中出现的次数
reduce : function(allSteps) {
var result = {};
for(var i=0; i
result[step.key] = result[step.key] ? (result[step.key] + 1) : 1;
}
return result;
},
//初始化,同时是运行的入口。
init : function() {
var allSteps = [];
for(var i=0; i
allSteps = allSteps.concat(Job.map(Job.data[i]));
}
//美中不足,这里不能多线程调用Job.reduce函数??
var result = Job.reduce(allSteps)
console.log(JSON.stringify(result));
}
}; // Job
//开始执行
Job.init();