Advertisement
Guest User

Untitled

a guest
Apr 27th, 2017
60
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.93 KB | None | 0 0
  1. const over = Symbol()
  2.  
  3. const isOver = function (_over) {
  4. return _over === over
  5. }
  6.  
  7. const range = function (from, to) {
  8. let i = from
  9. return function () {
  10. if (i++ < to) {
  11. console.log('range\t', i)
  12. return i
  13. }
  14. return over
  15. }
  16. }
  17.  
  18. const map = function (flow, transform) {
  19. return function () {
  20. const data = flow()
  21. console.log('map\t', data)
  22. return isOver(data) ? data : transform(data)
  23. }
  24. }
  25.  
  26. const filter = function (flow, condition) {
  27. return function () {
  28. while (true) {
  29. const data = flow()
  30. if (isOver(data)) {
  31. return data
  32. }
  33. if (condition(data)) {
  34. console.log('filter\t', data)
  35. return data
  36. }
  37. }
  38. }
  39. }
  40.  
  41. const stop = function (flow, condition) {
  42. let _stop = false
  43. return function () {
  44. if (_stop) return over
  45. const data = flow()
  46. if (isOver(data)) {
  47. return data
  48. }
  49. _stop = condition(data)
  50. return data
  51. }
  52. }
  53.  
  54. const take = function (flow, num) {
  55. let i = 0
  56. return stop(flow, data => {
  57. return ++i >= num
  58. })
  59. }
  60.  
  61. const join = function (flow) {
  62. const array = []
  63. while (true) {
  64. const data = flow()
  65. if (isOver(data)) {
  66. break
  67. }
  68. array.push(data)
  69. }
  70. return array
  71. }
  72.  
  73. function _Lazy() {
  74. this.iterator = null
  75.  
  76. this.range = function (from, to) {
  77. this.iterator = range(from, to)
  78. return this
  79. }
  80.  
  81. this.map = function(mapFn) {
  82. this.iterator = map(this.iterator, mapFn)
  83. return this
  84. }
  85.  
  86. this.filter = function (filterFn) {
  87. this.iterator = filter(this.iterator, filterFn)
  88. return this
  89. }
  90.  
  91. this.take = function (n) {
  92. this.iterator = take(this.iterator, n)
  93. return this
  94. }
  95.  
  96. this.join = function () {
  97. return join(this.iterator)
  98. }
  99. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement