123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130 |
- // ES6
- // a
- let a = text => alert(text);
- // cube
- let cube = (a) => a * a * a;
- // avg2
- let avg2 = (a, b) => (a + b) / 2;
- // sum3
- let sum3 = (a = 0, b = 0, c = 0) => a + b + c;
- // intRandom
- let intRandom = (a = 0, b = 0) => Math.round(Math.random() * (b - a)) + a;
- // greetAll
- let greetAll = (...arguments) => {
- for (let i in arguments) {
- alert('"' + 'Hello' + ' ' + arguments[i] + '"');
- }
- }
- // sum
- let sum = (...arguments) => {
- let sum = 0;
- for (let i = 0; i < arguments.length;i++) {
- sum += arguments[i];
- }
- return sum;
- }
- // sort
- function byField(field, order) {
- let collator = new Intl.Collator(["en", "ru"], {
- numeric: true
- })
- order = order ? 1 : -1;
- return function(a, b) {
- return order * collator.compare(a[field], b[field]);
- }
- }
- let users = [{
- name: "Иван",
- age: 17,
- }, {
- name: "Мария",
- age: 35,
- }, {
- name: "Алексей",
- age: 73,
- }, {
- name: "Яков",
- age: 12,
- }]
- users.sort(byField('age', true)); //сортирует по возрасту по возрастанию
- users.sort(byField('name', true)); //сортирует по имени по убыванию
- // array map
- let Array = ["1", {}, null, undefined, "500", 700];
- let result = Array.map(function(item) {
- let number = parseInt(item);
- return isNaN(number)? item : number;
- })
- console.log(result);
- // array reduce
- let arr = ["0", 5, 3, "string", null];
- let result = arr.reduce(function(previousValue, currentValue) {
- return typeof currentValue == 'number' ? previousValue * currentValue : previousValue;
- },1);
- console.log(result);
- // object filter
- function filter(obj, callback) {
- let mainObj = {};
- for(let key in obj) {
- if (callback(key, obj[key])) {
- mainObj[key] = obj[key];
- }
- }
- return mainObj;
- }
- let phone = {
- brand: "meizu",
- model: "m2",
- ram: 2,
- color: "black",
- }
- let outcome = filter(phone,(key,value) => key == "color" || value == 2);
- console.log(outcome);
- // object map
- function map(object, callback) {
- let obj = {};
- for(let key in object)
- Object.assign(obj,callback(key, object[key]));
- return obj;
- }
- let obj = map({name: 'Иван', age: 17}, function(key, value) {
- let result = {};
- result[key+"_"] = value + "$";
- return result;
- })
- console.log(obj);
- //возвращает {name_: "Иван$", age_: "17$"}
- // Sum
- // pешение с помощью цикла
- function sum(n) {
- let sum = 0;
- for (let i = 1;i <= n;i++) {
- sum += i;
- }
- return sum;
- }
- // or
- // pешение через рекурсию
- function sum(n) {
- if (n == 1) return 1;
- return n + sumTo(n - 1);
- }
|