Michael Fogus の本Functional JavaScriptを読んでいますが、本の例の 1 つが機能していません。コードは次のとおりです。
function existy(x) {
return x != null;
};
function truthy(x) {
return (x !== false) && existy(x);
};
function cat() {
var head = _.first(arguments);
if (existy(head))
return head.concat.apply(head, _.rest(arguments));
else
return [];
};
function construct(head, tail) {
return cat([head], _.toArray(tail));
};
function rename(obj, newNames) {
return _.reduce(newNames, function(o, nu, old) {
console.log("o: " + o);
console.log("nu: " + nu);
console.log("old: " + old);
if (_.has(obj, old)) {
o[nu] = obj[old];
return o;
}
else
return o;
},
_.omit.apply(null, construct(old, _.keys(newNames))));
};
rename({a: 1, b: 2}, {'a': 'AAA'});
// => {AAA: 1, b: 2}
rename() を除くすべての関数が正常に動作します。基本的に、オブジェクトを取得し、newName オブジェクトで更新されたプロパティ名を持つオブジェクトを返すことが目標です。私はそれを完全には理解していませんが、reduce メソッドは正しい引数を持っているようには見えません。rename() を呼び出したときに発生するエラーは次のとおりです。
ReferenceError: old is not defined
なぜそれが機能しないのかを理解するための助けをいただければ幸いです!