This looks to pass the requirements. I am sure someone can come up with a more eloquent answer. But the tricky parts are related to mostly the step parameter (negative and 0) and backwards movement (end < start) and the fact that it tries to do the "right" thing (stepping from 0 to -3 should not be possible witha step of 1, but it seems to automatically flip the step to be negative [again from reading the tests]).
function range (start, end, step = 1) {
if (end === undefined && start !== undefined) {
end = start;
start = 0;
}
// step should be negative if end is less than start
if (end < start && step > 0) {
step = step * -1
}
// if the step is 0 you will never allocate the correct array length
const stepSize = (step == 0) ? 1 : step
const size = Math.abs(Math.ceil((end - start) / stepSize))
// need to exit if there is nothing to return
if (size == Infinity) {
return []
}
// step has some really odd behavior (from tests)
// specifically a step of 0, which seems to repeat the start?
const incrementStep = (x, y) =>
(step == 0) ? start : x + y * step
return Array(size).
fill(start).
map(incrementStep)
}
console.log(range(4)); // => [0, 1, 2, 3]
console.log(range(-4)); // => [0, -1, -2, -3]
console.log(range(1, 5)); // => [1, 2, 3, 4]
console.log(range(0, 20, 5)); // => [0, 5, 10, 15]
console.log(range(0, -4, -1)); // => [0, -1, -2, -3]
console.log(range(1, 4, 0)); // => [1, 1, 1]
console.log(range(0)); // => []
Run code snippetEdit code snippet Hide Results Copy to answer Expand
Answer from akaphenom on Stack Overflow
» npm install lodash.range
» npm install @types/lodash.range
I am trying to use the lodash _.filter function to filter a range of values between for example 43 and 47. I have gotten it to filter out everything that is lower then 43 but I don’t know how to filter it for numbers above 47.
I know this is probably relatively simple, but I cant find by googling how to write it correctly.
var charactersStar = [
{ 'user': 'trump', 'rank': 36, 'active': true },
{ 'user': 'fred', 'rank': 30, 'active': false },
{ 'user': 'luke', 'rank': 47, 'active': true },
{ 'user': 'hillary', 'rank': 44, 'active': false },
{ 'user': 'bernie', 'rank': 36, 'active': true },
{ 'user': 'john', 'rank': 40, 'active': false },
{ 'user': 'pebbles', 'rank': 1, 'active': true }
];
var result = _.filter(charactersStar, function(o) {
return o.rank > 42;
});
console.log(result);You just need to use the "and" operator which is &&
var result = _.filter(charactersStar, function(o)
return o.rank > 42 && o.rank <48 ;
});
In addition to the other fine answers, unless you need to support a very old browser (e.g. IE 8), you can use javascript's native array filter function.
E.g.
var result = charactersStar.filter(function (item) {
return item.rank >= 43 && item.rank <= 47;
}