7 kyu

Sequence generator

Description:

Implement function sequence, which returns new n-size Array filled according to pattern.

pattern may be:

  • a function that takes two: (element, index), one: (element) or any arguments (similar to map function), then filled running this function, in other words: function describes sequence,
  • number, string or any other object, then filled by copying, this object n-times.

Examples:

sequence(3, 4); // [4, 4, 4]
sequence(5, []); // [[], [], [], [], []]
sequence(2, "s"); // ["s", "s"]
sequence(5, (x, idx) => idx%2) // [0, 1, 0, 1, 0];
sequence(10, (x, idx) => idx+1) // [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Note: Sequences are great to work with functional methods like map, reduce, forEach, every or any. For example:

// sum of numbers 1-10
let sum = sequence(10, (x, idx) => idx+1).reduce((sum, num) => sum + num);

Be careful with long sequences. They are just arrays, every element is created when function is called.

For lazy sequences (elements created when needed) use Iterator.

Arrays
Functional Programming
Fundamentals

More By Author:

Check out these other kata created by czterystaczwarty

Stats:

CreatedFeb 10, 2016
PublishedFeb 10, 2016
Warriors Trained6450
Total Skips34
Total Code Submissions26872
Total Times Completed5046
JavaScript Completions5046
Total Stars31
% of votes with a positive feedback rating83% of 369
Total "Very Satisfied" Votes271
Total "Somewhat Satisfied" Votes74
Total "Not Satisfied" Votes24
Ad
Contributors
  • czterystaczwarty Avatar
  • sajadtorkamani Avatar
  • myjinxin2015 Avatar
  • Voile Avatar
Ad