-
Notifications
You must be signed in to change notification settings - Fork 55
/
js_builtins.js
70 lines (52 loc) · 2.13 KB
/
js_builtins.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
"use strict";
window.builtins = {};
// In this exercise, we'll be recreating some common JavaScript built-in
// functions such as contains() and trim() using the skills we already know.
// For a reference to all JavaScript built-in objects and functions,
// check out this MDN reference:
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects
// ----------------------------------------------------------------------------
// Exercise 1. trim() using loops and conditionals
// Write a function that takes a string and returns the same string without
// leading and trailing spaces.
// ex. builtins.trim(' Horizons ') -> 'Horizons'
// ex. builtins.trim('Hello World! ') -> 'Hello World!'
builtins.trim = function(str) {
let newStr = "";
for (let i = 0; i < str.length; i++) {
if (str[i] !== " ") {
newStr += str[i];
}
}
return newStr;
};
// ----------------------------------------------------------------------------
// Exercise 2. contains() using indexOf()
// Write a function that takes a string to be searched and a string to
// search for, returning true or false as to whether or not the latter
// was found in the source string.
// ex. builtins.search('Horizons', 'o') -> true
// ex. builtins.search('Horizons', 'oz') -> false
// ex. builtins.search('rizo', 'Horizons') -> false
// ex. builtins.search('', 'Horizons') -> false
// ex. builtins.search('Horizons', '') -> true
// ex. builtins.search('Horizons', 'h') -> false
builtins.search = function(sourceString, searchString) {
if (searchString.indexOf(sourceString)) {
return true;
} else {
return false;
}
};
// ----------------------------------------------------------------------------
// Exercise 3. Rewriting reverse()
// Write a function that takes an array and returns the array in reversed order
// (by indices).
// ex. builtins.reverse([1, 2, 3]) -> [3, 2, 1]
// ex. builtins.reverse(['dogs', 'cats', 'moose']) -> ['moose', 'cats', 'dogs']
// ex. builtins.reverse([]) -> []
// ex. builtins.reverse([123]) -> [123]
builtins.reverse = function(arr) {
let next = arr.unshift();
return builtins.reverse(arr).concat(next);
};