An article with you to understand the basis of the algorithm in JavaScript "String class"

file

Author | Jeskson

Source | Dada front-end bistro

1

Algorithm can do? What to improve? what are the benefits?

Students need to upgrade the front-end programming core internal strength, establish and improve the algorithm knowledge, basic algorithms, data structures, advanced algorithms, progressive approach to explain, a thorough understanding of the abstract algorithm, algorithm interview is a key element, the impact of front-end manufacturers offer.

Before learning algorithms to master ES6 Oh! You need to know unit testing language, Jest

file

Jest is a delightful JavaScript Testing Framework with a focus on simplicity.

It works with projects using: Babel, TypeScript, Node, React, Angular, Vue and more!

Jest is a very pleasant JavaScript testing framework, focusing on simplicity.

It is suitable for the use of project the following items: Babel, TypeScript, Node, React, Angular, Vue and so on!

zero config

Jest aims to work out of the box, config free, on most JavaScript projects.

Zero Configuration
Jest aimed at the majority of JavaScript projects out of the box, no configuration.

snapshots

Make tests which keep track of large objects with ease. Snapshots live either alongside your tests, or embedded inline.

Snapshot

Test to easily keep track of large objects. Snapshots can coexist with the test, it can also be embedded embedding.

isolated

Tests are parallelized by running them in their own processes to maximize performance.

isolated

By running their own tests to parallelize processes to maximize their performance.

great api

From it to expect - Jest has the entire toolkit in one place. Well documented, well maintained, well good.

Great api

From to expect-Jest entire toolkit in one place. Well documented, well maintained, very good.

Jest automated testing features:

Quick security
code coverage
relaxed simulation

Basic algorithms: a string type, an array class, category sorting, recursive type, regular class.

Data structures: heap, stack, queue, list, matrix, binary tree.

Learning Jest, Getting Started, using yarn installation Jest:

yarn add --dev jest

Or usenpm

npm install --save-dev jest

Write a function of the sum of two numbers:

function sum(a,b) {
 return a + b;
}

module.exports = sum;

Test file

const sum = require('./sum');
// 测试我们的相加函数文件

test('adds 1+2 to equal 3', () => {
 expect(sum(1,2)).toBe(3);
});

Configurationpackage.json

{
 "scripts": {
  "test": "jest"
 }
}

Jest is Facebook launched a testing framework that integrates Mocha, chai, jsdom other functions.

Installation configuration

npm install --save-dev jest

npm install -g jest

The latter run the command jest, will automatically run the project file and all .test.js .spec.js files, jest default configuration needs only to configure package.json.

The jest operating range limit in the test folder, package.json added

"jest" {
 "testRegex": "/test/.*.test.jsx?$"
}

Jest is a very easy to use testing tools, let in several small steps to actually operate it.

需要新建一个js文件名为sum

// sum.js
function sum (value1, value2) {
 return value1 + value2;
}
module.exports = sum;

sum-test.js

// _tests_/sum-test.js
jest.dontMock('../sum');

describe('sum', function() {
 it('add 1 + 2 to equal 3', function() {
  var sum = require('../sum');
  expect(sum(1,2)).toBe(3);
 });
});

package.json代码

{
 "scripts": {
   "test": "jest"
 }
}

执行命令 "npm test" 或 "jest"

file

npm install --save-dev jest

file

npm run test Jest

Jest-Test

https://github.com/huangguangda/Jest-Test

file

master分支:

git checkout master

环境搭建

dev分支:

所有源码

git checkout div

给定一个整数的数组和一个目标值target:

给定 nums = [2, 7, 11, 15], target = 9

因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]

file

<template>
  <view class="content">
    <image class="logo" src="/static/logo.png"></image>
    <view class="text-area">
      <text class="title">{{da[0]}} + {{da[1]}}</text>
    </view>
    <button @click="twoSum">点击两数之和</button>
  </view>
</template>
<!-- 给定 nums = [2, 7, 11, 15], target = 9

因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1] -->
<script>
  export default {
    data() {
      return {
        nums: [2, 7, 11, 15],
        target: 9,
        title: 'Hello',
        da: [],
      }
    },
    onLoad() {

    },
    // nums[0] + nums[1] = 2 + 7 = 9
    // [0, 1] 
    methods: {
      twoSum:function() {
        // 数组长度
        var len = this.nums.length;
        // 目标数组
          var nums = this.nums;
        // 两数之和
        var target = this.target;
        // [0, 1] 设置da数组
        var da = [];
        // 循环
        for(var i=0; i<len; i++) {
          for(var j = i+1; j<len; j++){
            if(nums[i] + nums[j] == target) {
              da[0] = i;
              da[1] = j;
            }
          }
        }
        return this.da = da;
      }
    }
  }
</script>

<style>
  .content {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
  }

  .logo {
    height: 200rpx;
    width: 200rpx;
    margin-top: 200rpx;
    margin-left: auto;
    margin-right: auto;
    margin-bottom: 50rpx;
  }

  .text-area {
    display: flex;
    justify-content: center;
  }

  .title {
    font-size: 36rpx;
    color: #8f8f94;
  }
</style>
/**
 * @param {number[]} nums
 * @param {number} target
 * @return {number[]}
 */
var nums = [2, 7, 11, 15], target = 9;
var twoSum = function(nums, target) {
    var da = [];
    for(var i=0; i<nums.length; i++) {
        for(var j=i+1; j<nums.length; j++) {
            if(nums[i] + nums[j] == target) {
                da[0] = i;
                da[1] = j;
            }
        }
    }
    return da;
};

file

给定一个字符串,你需要反转字符串中每个单词的字符顺序,同时仍保留空格和单词的初始顺序。

输入: "Let's take LeetCode contest"
输出: "s'teL ekat edoCteeL tsetnoc" 

JavaScript join() 方法

定义和用法

join() 方法用于把数组中的所有元素放入一个字符串。
元素是通过指定的分隔符进行分隔的。

JavaScript reverse() 方法

定义和用法
reverse() 方法用于颠倒数组中元素的顺序。

JavaScript split() 方法

定义和用法
split() 方法用于把一个字符串分割成字符串数组。

/**
 * @param {string} s
 * @return {string}
 */
var s = "Let's take LeetCode contest";
var reverseWords = function(s) {
    // 字符串按空格进行分隔,保存数组,数组的元素的先后顺序就是单词的顺序
    // 字符串变数组
    var daArray = s.split(' ');
    // 将字符串按空格分开变成数组
    // for(var i=0; i<daArray.length; i++) {
        // 将数组中的各个元素分别分开、反转、重新变成字符串,然后将当前数组元素重新赋值
        // daArray[i] = daArray[i].split('').reverse().join("");
    // }
    // 返回时将数组中的元素用空格隔开,变成字符串
    // return daArray.join('');
    // var result = daArray.reverse().join(' ');
    var result = daArray.map( item => {
        return item.split('').reverse().join('')
    })
    return result.join(' ');
};
/**
 * @param {string} s
 * @return {string}
 */
var s = "Let's take LeetCode contest";
var reverseWords = function(s) {
    // 字符串按空格进行分隔,保存数组,数组的元素的先后顺序就是单词的顺序
    // 字符串变数组
    var daArray = s.split(' ');
    // 将字符串按空格分开变成数组
    for(var i=0; i<daArray.length; i++) {
        // 将数组中的各个元素分别分开、反转、重新变成字符串,然后将当前数组元素重新赋值
        daArray[i] = daArray[i].split('').reverse().join("");
    }
    // 返回时将数组中的元素用空格隔开,变成字符串
    return daArray.join(' ');
    // var result = daArray.reverse().join(' ');
    // var result = daArray.map( item => {
    //     return item.split('').reverse().join('')
    // })
    // return result.join(' ');
};

代码优雅:

return str.split(' ').map(item => {
 return item.split('').reverse().join('')
}).join(' ');

字符串方法:

String.prototype.split
String.prototype.match

数组的方法

Array.prototype.map
Array.prototype.reverse
Array.prototype.join

给定一个字符串 s,计算具有相同数量0和1的非空(连续)子字符串的数量,并且这些子字符串中的所有0和所有1都是组合在一起的。

重复出现的子串要计算它们出现的次数。

file

var s = "00110011"

curlen 与 prelen 分别记录当前数字出现次数与前半部分数字出现
/**
 * @param {string} s
 * @return {number}
 */
var s = "00110011"
var countBinarySubstrings = function(s) {
    let result = 0; 
    // curLen 与 preLen 分别记录当前数字出现次数与前半部分数字出现次数
    let curLen = 1; // 当前数字
    let preLen = 0; // 下一个数字
    for (let i = 0; i < s.length - 1; i++) {
        // 指针往后移动,若当前数字与下一个数字一样则将curLen加1
        if (s[i] === s[i + 1]) {
            curLen += 1;
        } else {
            // 否则就是遇到了不同之处,把相同子串的长度交给preLen
            // curLen再重新往后寻找
            preLen = curLen;
            curLen = 1;
        }
        // curLen小于等于prLen则符合条件
        if (preLen >= curLen) {
            result += 1;
        }
    }
    return result;
};
示例 2 :

输入: "10101"
输出: 4
解释: 有4个子串:“10”,“01”,“10”,“01”,它们具有相同数量的连续1和0。

file

上面的截图才是有效的子串。数串串。

❤️ 不要忘记留下你学习的脚印 [点赞 + 收藏 + 评论]

作者Info:

[Author]: Jeskson
[original] Public number: Dada front-end bistro.
[Welfare]: No public reply "Information" self-study materials sent to spree (into the group to share what you want to say Ha, I did not see)!
[Reserved] Description: reproduced please indicate the source, thank you! ~

Large front-end development, front-end development positioning technology stack blog, PHP background knowledge, web full stack technology fields, data structures and algorithms, and so easy to understand network theory is presented to the junior partner. Thank you support, courtesy of love! ! !


If this number of local contents do not get bits (for example: to copyright or other problems), please contact us for rectification can be timely and will be processed in the first time.


Please thumbs up! Because you agree / encouragement is the greatest power of my writing!

Welcome attention to Dada 's CSDN!

This is a quality, attitude blog

Front-end technology stack

Guess you like

Origin www.cnblogs.com/dashucoding/p/12117844.html
Recommended