Last active
December 22, 2015 00:38
-
-
Save xiaoyvr/6390634 to your computer and use it in GitHub Desktop.
DSL of setValueOf
This file contains 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
function setValueOf(fieldName, obj) { | |
var originVal = obj[fieldName] || {}; | |
var getters = []; | |
var builder = { | |
inRange: function (collection, findKey) { | |
getters.push(function () { | |
return _.find(collection, function (i) { | |
return findKey ? (i[findKey] === originVal[findKey]) : (i === originVal); | |
}); | |
}); | |
return builder; | |
}, | |
otherwise: function (defaultVal) { | |
getters.push(function () { | |
return defaultVal; | |
}); | |
return builder; | |
}, | |
set: function () { | |
for (var i = 0; i < getters.length; i++) { | |
var v = getters[i](); | |
if (v !== undefined && v !== null) { | |
obj[fieldName] = v; | |
break; | |
} | |
} | |
} | |
}; | |
return builder; | |
} | |
var x = {}; | |
x.t = 4; | |
setValueOf('t', x).inRange([1, 2, 3]).set(); | |
console.log(x.t) | |
x.t = 4; | |
setValueOf('t', x).inRange([1, 2, 3]).otherwise(0).set(); | |
console.log(x.t) | |
x.t = 4; | |
setValueOf('t', x).inRange([1, 2, 3, 4]).otherwise(0).set(); | |
console.log(x.t); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment