# Learn Functional Programming by Building a Spreadsheet - Step 98

### Tell us what’s happening:

I tried the slice method, but it’s not working; although I tried following directions.

``````<!-- file: index.html -->
<!DOCTYPE html>
<html lang="en">
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<body>
<div id="container">
<div></div>
</div>
<script src="./script.js"></script>
</body>
</html>
``````
``````/* file: styles.css */
#container {
display: grid;
grid-template-columns: 50px repeat(10, 200px);
grid-template-rows: repeat(11, 30px);
}

.label {
background-color: lightgray;
text-align: center;
vertical-align: middle;
line-height: 30px;
}
``````
``````/* file: script.js */
const infixToFunction = {
"+": (x, y) => x + y,
"-": (x, y) => x - y,
"*": (x, y) => x * y,
"/": (x, y) => x / y,
}

const infixEval = (str, regex) => str.replace(regex, (_match, arg1, operator, arg2) => infixToFunction[operator](parseFloat(arg1), parseFloat(arg2)));

const highPrecedence = str => {
const regex = /([\d.]+)([*\/])([\d.]+)/;
const str2 = infixEval(str, regex);
return str === str2 ? str : highPrecedence(str2);
}

const isEven = num => num % 2 === 0;
const sum = nums => nums.reduce((acc, el) => acc + el, 0);
const average = nums => sum(nums) / nums.length;

const median = nums => {
const sorted = nums.slice().sort((a, b) => a - b);
const length = sorted.length;
const middle = length / 2 - 1;
return isEven(length)
? average([sorted[middle], sorted[middle + 1]])
: sorted[Math.ceil(middle)];
}

// User Editable Region

sum,
average,
median,
even: nums => nums.filter(isEven),
firsttwo: nums.slice(0, 2),
lasttwo: nums.slice(-2)
}

// User Editable Region

const applyFunction = str => {
const noHigh = highPrecedence(str);
const infix = /([\d.]+)([+-])([\d.]+)/;
const str2 = infixEval(noHigh, infix);
const functionCall = /([a-z0-9]*)\(([0-9., ]*)\)(?!.*\()/i;
const toNumberList = args => args.split(",").map(parseFloat);
const apply = (fn, args) => spreadsheetFunctions[fn.toLowerCase()](toNumberList(args));
return str2.replace(functionCall, (match, fn, args) => spreadsheetFunctions.hasOwnProperty(fn.toLowerCase()) ? apply(fn, args) : match);
}

const range = (start, end) => Array(end - start + 1).fill(start).map((element, index) => element + index);
const charRange = (start, end) => range(start.charCodeAt(0), end.charCodeAt(0)).map(code => String.fromCharCode(code));

const evalFormula = (x, cells) => {
const idToText = id => cells.find(cell => cell.id === id).value;
const rangeRegex = /([A-J])([1-9][0-9]?):([A-J])([1-9][0-9]?)/gi;
const rangeFromString = (num1, num2) => range(parseInt(num1), parseInt(num2));
const elemValue = num => character => idToText(character + num);
const addCharacters = character1 => character2 => num => charRange(character1, character2).map(elemValue(num));
const rangeExpanded = x.replace(rangeRegex, (_match, char1, num1, char2, num2) => rangeFromString(num1, num2).map(addCharacters(char1)(char2)));
const cellRegex = /[A-J][1-9][0-9]?/gi;
const cellExpanded = rangeExpanded.replace(cellRegex, match => idToText(match.toUpperCase()));
const functionExpanded = applyFunction(cellExpanded);
return functionExpanded === x ? functionExpanded : evalFormula(functionExpanded, cells);
}

const container = document.getElementById("container");
const createLabel = (name) => {
const label = document.createElement("div");
label.className = "label";
label.textContent = name;
container.appendChild(label);
}
const letters = charRange("A", "J");
letters.forEach(createLabel);
range(1, 99).forEach(number => {
createLabel(number);
letters.forEach(letter => {
const input = document.createElement("input");
input.type = "text";
input.id = letter + number;
input.ariaLabel = letter + number;
input.onchange = update;
container.appendChild(input);
})
})
}

const update = event => {
const element = event.target;
const value = element.value.replace(/\s/g, "");
if (!value.includes(element.id) && value.startsWith('=')) {
element.value = evalFormula(value.slice(1), Array.from(document.getElementById("container").children));
}
}
``````

User Agent is: `Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Safari/537.36`

### Challenge Information:

Learn Functional Programming by Building a Spreadsheet - Step 98

1 Like

This should be a function that takes `nums` array as parameter, and return the first two elements of the given `nums` array.

Same thing as the previous line:

1 Like

Thanks for the confirmation. That’s what I was missing.

please tell me why the nums.slice has (0, 2 ) shouldn’t it be 0, 1 …and why the -2 in the lasttwo

an explaination would be wonderful

Hi there,

The syntax of the array function `slice` is:

``````Array.slice(start_index, end_index)
``````

this will return a new array which is a portion of `Array` consists of elements from `start_index` to `end_index` (but element at `end_index` is not included).

For example:

``````const nums = [10, 20, 30, 40, 50, 60, 70]
``````
``````nums.slice(0, 2)
``````

will return `[10, 20]` because it will start from the first element (index `0`) and end at the third element (index `2`) but not include the third element.

``````nums.slice(1, 4)
``````

will return `[20, 30, 40]`.

One thing we need to remember is:

Array is zero-based index. Which means the first element’s index is `0`, not `1`.

The last element’s index is `-1`.
The seconde last element’s index is `-2`, and so on…

`nums[-1]` is `70`
`nums[-2]` is `60`

You can read more about `Array.slice()` in the document on MDN:

On a side note, if you don’t remember about any function, you can search about that function on the document.
This is a good habit for programmer as we can’t remember all the syntax.

These are my go-to sites to look up documentation:

Happy coding!

4 Likes

thank you for your detailed explanation …i searched Google and got confused

1 Like

Sorry, I missed this question.

If only one argument is provide for `Array.slice()` instead of two arguments, then that argument is `start_index`.

`Array.slice(start_index) ` will return the sub-array that start from `start_index` till the end of `Array`.

``````const nums = [10, 20, 30, 40, 50, 60, 70]

nums.slice(1) // return [20, 30, 40, 50, 60, 70]
nums.slice(2) // return [30, 40, 50, 60, 70]
nums.slice(-2) // return [60, 70]
``````
2 Likes