util.js 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113
  1. var Rx = require('cyclejs').Rx;
  2. var _ = require('lodash');
  3. // modified from https://github.com/JedWatson/classnames/blob/master/index.js
  4. function classNames () {
  5. var classes = '';
  6. for (var i = 0; i < arguments.length; i++) {
  7. var arg = arguments[i];
  8. if (!arg) continue;
  9. var argType = typeof arg;
  10. if ('string' === argType || 'number' === argType) {
  11. classes += '.' + arg;
  12. } else if (Array.isArray(arg)) {
  13. classes += '.' + classNames.apply(null, arg);
  14. } else if ('object' === argType) {
  15. for (var key in arg) {
  16. if (arg.hasOwnProperty(key) && arg[key]) {
  17. classes += '.' + key;
  18. }
  19. }
  20. }
  21. }
  22. return classes;
  23. }
  24. function log(label) {
  25. return _.bind(console.log, console, label);
  26. }
  27. function flatten(obj) {
  28. var ret = {};
  29. _.forEach(obj, function(val, key) {
  30. if(_.isPlainObject(val)) {
  31. var o = flatten(val);
  32. _.forEach(o, function(val, innerKey) {
  33. ret[key+'.'+innerKey] = val;
  34. });
  35. }
  36. else {
  37. ret[key] = val;
  38. }
  39. });
  40. return ret;
  41. }
  42. function _set(obj, key, val) {
  43. var pos = key.indexOf('.');
  44. if(pos < 0) {
  45. obj[key] = val;
  46. }
  47. else {
  48. var parent = key.substr(0, pos);
  49. if(!obj[parent]) {
  50. obj[parent] = {};
  51. }
  52. var rest = key.substr(pos+1);
  53. _set(obj[parent], rest, val);
  54. }
  55. }
  56. function unflatten(obj) {
  57. var ret = {};
  58. var set = _.bind(_set, null, ret);
  59. _.forEach(obj, function(val, key) {
  60. set(key, val);
  61. });
  62. return ret;
  63. }
  64. function asObject(params) {
  65. params = flatten(params);
  66. var keys = _.keys(params).map(function(key) {
  67. return key.replace(/\$$/, '');
  68. });
  69. var vals = _.values(params);
  70. return Rx.Observable.combineLatest(vals, function() {
  71. return unflatten(_.zipObject(keys, arguments));
  72. });
  73. }
  74. function sync(trigger$, data$) {
  75. return trigger$.withLatestFrom(data$, function(a, b) {
  76. return b;
  77. });
  78. }
  79. function PropertyHook(fn) {
  80. this.fn = fn;
  81. }
  82. PropertyHook.prototype.hook = function() {
  83. this.fn.apply(this, arguments);
  84. }
  85. function propHook(fn) {
  86. return new PropertyHook(fn);
  87. }
  88. module.exports = {
  89. asObject: asObject,
  90. sync: sync,
  91. log: log,
  92. classNames: classNames,
  93. propHook: propHook
  94. };