Browse Source

[select] select-return now works for arrays and iterables.

//TODO:
* Documentation
pull/1/head
Muthu Kumar 7 years ago
parent
commit
f8a5159da9
  1. 1
      .eslintrc.js
  2. 60
      Select.js
  3. 20
      spec/SelectArraySpec.js

1
.eslintrc.js

@ -29,7 +29,6 @@ module.exports = {
camelcase: 'warn',
'capitalized-comments': 'error',
'class-methods-use-this': 'error',
'comma-dangle': 'error',
'comma-spacing': 'error',
'comma-style': 'error',
complexity: 'error',

60
Select.js

@ -1,21 +1,67 @@
'use strict';
const isIterable = val => typeof val === "object" && Symbol.iterator in val;
class Select {
class SelectValue {
constructor(value, resolve) {
this.value = value;
this.iterable = isIterable(value);
if (resolve) this.resolve = resolve;
}
}
SelectValue.prototype.resolve = () => null;
class SelectIterable {
constructor(values, tests) {
this.values = values
.map(x => x instanceof SelectValue
? x
: new SelectValue(x)
);
this.tests = tests;
}
for(test, consequent) {
const self = this;
return new SelectIterable(
self.values,
[ ...self.tests, { test, consequent } ]
);
}
}
/* eslint-disable-next-line func-names */
SelectIterable.prototype.resolve = function (...args) {
const self = this;
return self.values.map(item => {
const resolve = self
.tests
/* eslint-disable-next-line */
.find(x => {
return x.test(item.value)
? x.consequent
: null;
});
return resolve
? resolve.consequent(...args, self.value)
: () => null;
});
};
class Select extends SelectValue {
constructor(value, resolve) {
super(value, resolve);
this.iterable = typeof value === "object" && Symbol.iterator in value;
}
for(test, consequent) {
if (this.iterable) {
return new SelectIterable(
Array.from(this.value),
[ { test, consequent } ],
);
}
if (test(this.value)) return new Select(this.value, consequent);
if (this.resolve) return this;
return this;
}
}
Select.prototype.resolve = () => null;
module.exports = Select;

20
spec/SelectArraySpec.js

@ -0,0 +1,20 @@
'use strict';
const Select = require('../Select');
/* global describe it expect */
describe("Select", () => {
it("Should return array [ 'Is 10', 'Greater than 10', 'Lesser than 10' ]",
() => {
const a = [ 10, 20, 0 ];
const result = new Select(a)
.for(x => x > 10, () => 'Greater than 10')
.for(x => x < 10, () => 'Lesser than 10')
.for(x => x === 10, () => `Is 10`);
expect(result.resolve())
.toEqual([ 'Is 10', 'Greater than 10', 'Lesser than 10' ]);
});
});
Loading…
Cancel
Save